Builder,建造模式:将一个复杂对象的构建与他的表示相分离,使得同样的构建过程可以创建不同的表示。
package com.cbf4life;
import java.util.ArrayList;
public abstract class CarModel {
private ArrayList<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++){
String actionName = this.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("engine boom")){
this.engineBoom();
}
}
}
final public void setSequence(ArrayList<String> sequence){
this.sequence = sequence;
}
}
package com.cbf4life;
public class BenzModel extends CarModel {
@Override
protected void alarm() {
System.out.println("奔驰车的喇叭声音是这个样子的...");
}
@Override
protected void engineBoom() {
System.out.println("奔驰车的引擎是这个声音的...");
}
@Override
protected void start() {
System.out.println("奔驰车跑起来是这个样子的...");
}
@Override
protected void stop() {
System.out.println("奔驰车应该这样停车...");
}
}
package com.cbf4life;
public class BMWModel extends CarModel {
@Override
protected void alarm() {
System.out.println("宝马车的喇叭声音是这个样子的...");
}
@Override
protected void engineBoom() {
System.out.println("宝马车的引擎是这个声音的...");
}
@Override
protected void start() {
System.out.println("宝马车跑起来是这个样子的...");
}
@Override
protected void stop() {
System.out.println("宝马车应该这样停车...");
}
}
package com.cbf4life;
import java.util.ArrayList;
public abstract class CarBuilder {
public abstract void setSequence(ArrayList<String> sequence);
public abstract CarModel getCarModel();
}
package com.cbf4life;
import java.util.ArrayList;
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);
}
}
package com.cbf4life;
import java.util.ArrayList;
public class BMWBuilder extends CarBuilder {
private BMWModel bmw = new BMWModel();
@Override
public CarModel getCarModel() {
return this.bmw;
}
@Override
public void setSequence(ArrayList<String> sequence) {
this.bmw.setSequence(sequence);
}
}
package com.cbf4life;
import java.util.ArrayList;
public class Client {
public static void main(String[] args) {
ArrayList<String> sequence = new ArrayList<String>();
sequence.add("engine boom");
sequence.add("start");
sequence.add("stop");
BenzBuilder benzBuilder = new BenzBuilder();
benzBuilder.setSequence(sequence);
BenzModel benz = (BenzModel)benzBuilder.getCarModel();
benz.run();
BMWBuilder bmwBuilder = new BMWBuilder();
bmwBuilder.setSequence(sequence);
BMWModel bmw = (BMWModel)bmwBuilder.getCarModel();
bmw.run();
}
}