不同于工厂模式,建造者模式在于不同的顺序
以下样例参考:设计模式之禅
package com.zhanchenkeji.createDesign;
import java.util.ArrayList;
import java.util.List;
public abstract class CarModel {
private List<SORT> list = new ArrayList<SORT>();
public List<SORT> getList() {
return list;
}
public void setList(List<SORT> list) {
this.list = list;
}
public abstract void start();// 启动
public abstract void alarm();// 鸣笛
public abstract void engineBoom();// 引擎
public abstract void stop();// 停止
public void run() {
for (SORT item : list) {
switch (item) {
case START:
start();
break;
case STOP:
stop();
break;
case ENGAGE:
engineBoom();
break;
case ALARM:
alarm();
break;
default:
break;
}
}
}
}
package com.zhanchenkeji.createDesign;
public class BMW extends CarModel{
@Override
public void start() {
System.out.println("BMO启动了");
}
@Override
public void alarm() {
// TODO Auto-generated method stub
System.out.println("BMO鸣笛");
}
@Override
public void engineBoom() {
// TODO Auto-generated method stub
System.out.println("BMO发动引擎");
}
@Override
public void stop() {
// TODO Auto-generated method stub
System.out.println("BMO停下了");
}
}
里面用到的枚举类
package com.zhanchenkeji.createDesign;
public enum SORT {
ALARM,START,ENGAGE,STOP
}
package com.zhanchenkeji.createDesign;
import java.util.List;
public abstract class Designer {
public abstract void setSequence(List<SORT> list);//设置序列
public abstract CarModel getModel();
}
package com.zhanchenkeji.createDesign;
import java.util.List;
public class BMWDesigner extends Designer {
private BMW bmw = new BMW();
@Override
public void setSequence(List<SORT> list) {
bmw.setList(list);
}
@Override
public CarModel getModel() {
return this.bmw;
}
}
测试类
package com.zhanchenkeji.createDesign;
import java.util.Arrays;
import java.util.Scanner;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
BMW bmw = (BMW) new BMWDesigner().getModel();
System.out.println("请按以下对应信息输入保存顺序:");
System.out.println("1:"+SORT.ALARM+" 2:"+SORT.START+" 3:"+SORT.ENGAGE+" 4:"+SORT.STOP);
SORT []values =SORT.values();//保存
SORT []sequenceSorts = new SORT[4];
for(int i=0;i<4;i++){
System.out.println("请输入数据:");
int k = new Scanner(System.in).nextInt();
if(k>0&&k<5){
sequenceSorts[i]=values[k-1];
}
}
bmw.setList(Arrays.asList(sequenceSorts));
bmw.run();
}
}