首页 > 代码库 > 建造者模式
建造者模式
模型图形:
Director --> Builder
|
ConcreteBuilder -----> Product
| | | | |
... RealBuilder .. .... RealProduct
public abstract class Product {
private ArrayList<String> sequence;
protected abstract void doSomething1();
protected abstract void doSomething2();
public void setSequence(ArrayList<String> al){
this.sequence = al;
}
public void doTheRealThing(){
for(int i = 0;i<this.sequence.size();i++){
if(this.sequence.get(i).equals("doSomething1")){
this.doSomething1();
}else if(this.sequence.get(i).equals("doSomething2")){
this.doSomething2();
}
}
}
}
public class RealProd1 extends Product {
@Override
protected void doSomething1() {
// TODO Auto-generated method stub
System.out.println("I am the doSomething1 in the RealProd1");
}
@Override
protected void doSomething2() {
// TODO Auto-generated method stub
System.out.println("I am the doSomething2 in the RealProd1");
}
}
public class RealProd1Builder implements Builder {
private RealProd1 p;
public void setSequence(ArrayList<String> al) {
// TODO Auto-generated method stub
p = new RealProd1();
p.setSequence(al);
}
public Product getProduct() {
// TODO Auto-generated method stub
return this.p;
}
}
public class Director {
public Product getRealProd1(){
ArrayList<String> al = new ArrayList<String>();
al.add("doSomething1");
al.add("doSomething2");
Product p = new RealProd1();
p.setSequence(al);
return p;
}
public Product getRealProd2(){
return null;
}
}
测试方法:
public static void main(String[] args) {
// TODO Auto-generated method stub
Director d = new Director();
d.getRealProd1().doTheRealThing();
}
说明:产品侧的类定义和模板方法类似,只是通过arraylist来动态设置具体方法的执行顺序,
建造侧类的定义:只有设置al和返回产品类。具体的al实例对象放到了director类来设置。故只要改director的al就可以控制prod的具体实现了。