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