Chapter 13 建造者模式
建造者模式又叫生成器模式:将一个产品的内部表象与产品的生成过程分割开来,从而可以使一个建造过程生成具有不同的内部表象的产品对象。
代码:
package xiao;
import java.util.ArrayList;
import java.util.List;
class Product{
List<String> parts = new ArrayList<String>();
public void add(String part){
parts.add(part);
}
public void show(){
System.out.println("begin----");
for(String part : parts){
System.out.println(part);
}
}
}
abstract class Builder{
protected abstract void BuildPartA();
protected abstract void BuildPartB();
protected abstract Product getResult();
}
class ConcreteBuilder1 extends Builder{
private Product product = new Product();
public void BuildPartA(){
product.add("equipment A");
}
public void BuildPartB(){
product.add("equipment B");
}
protected Product getResult(){
return product;
};
}
class ConcreteBuilder2 extends Builder{
private Product product = new Product();
public void BuildPartA(){
product.add("equipment X");
}
public void BuildPartB(){
product.add("equipment Y");
}
protected Product getResult(){
return product;
};
}
class Director{
public void construct(Builder builder){
builder.BuildPartA();
builder.BuildPartB();
}
}
public class abc {
public static void main(String[] args) {
Director director = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
director.construct(b1);
Product p1 = b1.getResult();
p1.show();
director.construct(b2);
Product p2 = b2.getResult();
p2.show();
}
}