标签:建造者模式
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(); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:建造者模式
原文地址:http://blog.csdn.net/cjvs9k/article/details/46945813