public abstract class Builder {
public abstract void buildEngine(String engine);
public abstract void buildCylinder(String cylinder);
public abstract void buildFrame(String frame);
public abstract Porsche create();
}
PorscheBuilder
具体实现创建的方法,用于创建车辆
public class PorscheBuilder extends Builder {
private Porsche porsche = new Porsche();
public void buildEngine(String engine) {
porsche.setEngine(engine);
}
public void buildCylinder(String cylinder) {
porsche.setCylinder(cylinder);
}
public void buildFrame(String frame) {
porsche.setFrame(frame);
}
public Porsche create() {
return porsche;
}
}
Director
指挥官, 负责创建过程中的流程编排
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public Porsche createPorsche(String engine, String cylinder, String frame) {
builder.buildEngine(engine);
builder.buildCylinder(cylinder);
builder.buildFrame(frame);
return builder.create();
}
}
客户端调用
class create {
public static void main(String[] args) {
Builder builder = new PorscheBuilder();
Director director = new Director(builder);
//组装车辆
director.createPorsche("engine","cylinder","frame");
}
}