建造者模式为创建者模式之一,目的就是将复杂对象的创建与使用进行分离,使用者不需要知道复杂对象是怎么创建的,只需要设置参数或者直接构建即可获取到相应的对象。
如下图所示:
director:指挥者,负责创建的顺序
builder:抽象创建者
concreteBuilder:具体创建者,负责对象的具体属性的设置
product:具体需要创建的对象
public class Car {
private String color;
private Double price;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"color='" + color + '\'' +
", price=" + price +
'}';
}
}
public interface Builder {
void buildColor();
void buildPrice();
Car builderCar();
}
public class MiniCarBuilder implements Builder{
private Car car = new Car();
@Override
public void buildColor() {
car.setColor("yello");
}
@Override
public void buildPrice() {
car.setPrice(12.0);
}
@Override
public Car builderCar() {
return this.car;
}
}
public class Director {
private Builder builder;
public Director(Builder builder){
this.builder = builder;
}
public Car create(){
this.builder.buildPrice();
this.builder.buildColor();
return this.builder.builderCar();
}
public static void main(String[] args) {
Director director = new Director(new MiniCarBuilder());
Car car = director.create();
System.out.println(car);
}
}