Builder Pattern
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
将一个复杂对象的构建与它的表示分离,使得同样的构造过程可以创建不同的表示。
BenzModel继承CarModel,实现业务,而涉及序列。
BenzBuilder类中有一个私有属性BenzModel,一个设置序列方法和获得BenzModel方法,通过建造者Builder设置序列并且获得对象。
产品
public abstract class CarModel {
private ArrayList<String> sequence = new ArrayList<String>();
public abstract void start();
public abstract void stop();
public abstract void alarm();
public abstract void engineBoom();
public void run() {
for (int i = 0; i < sequence.size(); i++) {
String actionName = sequence.get(i);
if (actionName.equalsIgnoreCase("start")) {
this.start();
} else if (actionName.equalsIgnoreCase("stop")) {
this.stop();
} else if (actionName.equalsIgnoreCase("alarm")) {
this.alarm();
} else if (actionName.equalsIgnoreCase("engineBoom")) {
this.engineBoom();
}
}
}
final public void setSequence(ArrayList<String> sequence) {
this.sequence = sequence;
}
}
public class BenzModel extends CarModel {
@Override
public void alarm() {
System.out.println("奔驰叫");
}
@Override
public void engineBoom() {
System.out.println("奔驰轰轰轰");
}
@Override
public void start() {
System.out.println("奔驰启动");
}
@Override
public void stop() {
System.out.println("奔驰停止");
}
}
建造者
public abstract class CarBuilder {
public abstract void setSequence(ArrayList<String> sequence);
public abstract CarModel getCarModel();
}
//奔驰组装者
public class BenzBuilder extends CarBuilder {
private BenzModel benz=new BenzModel(); //这里是关键
@Override
public CarModel getCarModel() {
return this.benz;
}
@Override
public void setSequence(ArrayList<String> sequence) {
this.benz.setSequence(sequence);
}
}
这里就可以随便组装啦
public static void main(String[] args) {
ArrayList<String> sequence=new ArrayList<String>();
sequence.add("start");
sequence.add("stop");
sequence.add("engineBoom");
BenzBuilder builder=new BenzBuilder();
builder.setSequence(sequence);
BenzModel benzModel=(BenzModel) builder.getCarModel();
benzModel.run();
}
优点
封装性好,只告知客户规则的使用即可
独立易扩建
使用场景
相同的方法,不同的执行顺序,产生不同的事件结果时
多个部位或零件,都可以转配到一个对象中,但是产生的运行结果不同时
关键还是顺序的问题