设计模式-建造者模式

设计模式-建造者模式
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示,属于创建型模式。
适用场景
创建对象需要很多步骤,但是步骤的顺序不一定固定;
如果一个对象有非常复杂的内容结果(很多属性)把复杂对象的创建和使用分离。
汽车类

public class Car {
    private String color;
    private String type;
    private Double price;
    private Date createTime;


    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "Car{" +
                "color='" + color + '\'' +
                ", type='" + type + '\'' +
                ", price=" + price +
                ", createTime=" + createTime +
                '}';
    }
}

Build汽车接口

public interface IBuilderCar {
    Car builder();
}

具体实现类,其中return this是为了满足链式变成

public class BuilderCar implements IBuilderCar {

    private Car car = new Car();

    public BuilderCar addColor(String color){
        car.setColor(color);
        return this;
    }

    public BuilderCar addType(String type) {
        car.setType(type);
        return this;
    }

    public BuilderCar addPrice(Double price) {
        car.setPrice(price);
        return this;
    }

    public BuilderCar addCreateTime(Date createTime) {
        car.setCreateTime(createTime);
        return this;
    }

    @Override
    public Car builder() {
        if(car.getCreateTime() == null) {
            car.setCreateTime(new Date());
        }
        return car;
    }
}

测试类

public class Test {
    public static void main(String[] args) {
        Car car = new BuilderCar()
                .addColor("白色")
                .addType("SUV")
                .builder();
        System.out.println(car);

    }
}

结果

Car{color='白色', type='SUV', price=null, createTime=Tue Mar 03 22:59:22 CST 2020}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值