Builder模式


/**抽象Product
* Created by marcopan on 17/10/23.
*/
public abstract class CarModel {
    private List<String> sequence = new ArrayList<String>();

protected abstract void start();
protected abstract void stop();
protected abstract void alarm();
protected abstract void engineBoom();

final public void run() {
for (int i = 0; i < this.sequence.size(); i ++) {
if ("start".equalsIgnoreCase(this.sequence.get(i))) {
this.start();
} else if ("stop".equalsIgnoreCase(this.sequence.get(i))) {
this.stop();
} else if ("alarm".equalsIgnoreCase(this.sequence.get(i))) {
this.alarm();
} else if ("engine boom".equalsIgnoreCase(this.sequence.get(i))) {
this.engineBoom();
}
}
}

final public void setSequence(List<String> sequence) {
this.sequence = sequence;
}

final public List<String> getSequence() {
return sequence;
}
}

/**抽象builder
* Created by marcopan on 17/10/23.
*/
public interface CarBuilder {
public abstract void setSequence(List<String> sequence);
//设置完毕顺序后,就可以直接拿到这个车辆模型了
public abstract CarModel getCarModel();
}

/**concrete builder
* Created by marcopan on 17/10/23.
*/
public class BMWBuilder implements CarBuilder {
private CarModel bmw = new BMWModel();

@Override
public void setSequence(List<String> sequence) {
this.bmw.setSequence(sequence);
}

@Override
public CarModel getCarModel() {
return this.bmw;
}
}

public class BenzBuilder implements CarBuilder {
private CarModel benz = new BenzModel(); //奔驰车模型

@Override
public void setSequence(List<String> sequence) {
this.benz.setSequence(sequence);
}

@Override
public CarModel getCarModel() {
return this.benz;
}
}

public class Director {
private List<String> sequence = new ArrayList<String>();
private CarBuilder benzBuilder = new BenzBuilder();
private CarBuilder bmwBuilder = new BMWBuilder();

//A顺序的奔驰车
public CarModel getABenzModel() {
this.sequence.clear();
this.sequence.add("start");
this.sequence.add("stop");
this.benzBuilder.setSequence(sequence);
return this.benzBuilder.getCarModel();
}

//B顺序的奔驰车
public CarModel getBBenzModel() {
this.sequence.clear();
this.sequence.add("engine boom");
this.sequence.add("start");
this.sequence.add("stop");
this.benzBuilder.setSequence(sequence);
return this.benzBuilder.getCarModel();
}

//C顺序的宝马车
public CarModel getCBMWModel() {
this.sequence.clear();
this.sequence.add("start");
this.sequence.add("alarm");
this.sequence.add("stop");
this.bmwBuilder.setSequence(sequence);
return this.bmwBuilder.getCarModel();
}

//D顺序的宝马车
public CarModel getDBMWModel() {
this.sequence.clear();
this.sequence.add("engine boom");
this.sequence.add("start");
this.bmwBuilder.setSequence(sequence);
return this.bmwBuilder.getCarModel();
}
}

public class Client {
public static void main(String[] args) {
Director director = new Director();

director.getABenzModel().run();
director.getBBenzModel().run();
director.getCBMWModel().run();
}
}
posted @ 2017-10-28 19:00  不停的奋斗  阅读(193)  评论(0编辑  收藏  举报