概述
一个复杂对象的构建往往需要构建很多部件,建造者模式将这些部件的构建抽取出来,当所有部件都构建完毕后才完成这个复杂对象的构建
场景
复杂产品按部件构建
实现
产品
/**
* 被构建的产品
*/
public class Car {
private String wheel;
private String body;
private String engine;
public void setWheel(String wheel) {
this.wheel = wheel;
}
public void setBody(String body) {
this.body = body;
}
public void setEngine(String engine) {
this.engine = engine;
}
@Override
public String toString() {
return "Car{" +
"wheel='" + wheel + '\'' +
", body='" + body + '\'' +
", engine='" + engine + '\'' +
'}';
}
}
抽象建造者
/**
* 抽象建造者
*/
public abstract class AbstrctBuilder {
public abstract CarBuilder buildWheel();
public abstract CarBuilder buildBody();
public abstract CarBuilder buildEngine();
public abstract Car buildUp();
}
具体建造者
/**
* 具体建造者
*/
public class CarBuilder extends AbstrctBuilder{
Car car = new Car();
@Override
public CarBuilder buildWheel() {
car.setWheel("超级耐用的轮子");
return this;
}
@Override
public CarBuilder buildBody() {
car.setBody("翡冷翠车身");
return this;
}
@Override
public CarBuilder buildEngine() {
car.setEngine("2.5T蓝鲸发动机");
return this;
}
@Override
public Car buildUp() {
return car;
}
}
指挥者
/**
* 指挥者
*/
public class Director {
AbstrctBuilder carBuilder;
public Director(AbstrctBuilder carBuilder) {
this.carBuilder = carBuilder;
}
public Car construct(){
return carBuilder.buildWheel().buildBody().buildEngine().buildUp();
}
}
测试
/**
* 测试
*/
public class BuilderTest {
@Test
public void testBuildder(){
AbstrctBuilder carBuilder = new CarBuilder();
Director director = new Director(carBuilder);
Car car = director.construct();
System.out.println(car);
}
}
测试结果
总结
1.构建者模式适合构建由复杂部分构成的对象,但是当被构建的产品内部发生变化时调整成本很大
2.可以将Builder每个构建部件的方法返回值设置为Buider,这样在调用的时候更加方便