本篇以思维导图结合例子介绍建造者模式
1 概念基础
2 例子
1)Builder
package com.szh.pattern;
public abstract class Builder {
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product getResult();
}
2)ConcreteBuilder
a.ConcreteBuilderA
package com.szh.pattern;
public class ConcreteBuilderA extends Builder {
private Product product = new Product();
@Override
public void BuildPartA() {
product.add("部件1.1");
}
@Override
public void BuildPartB() {
product.add("部件1.2");
}
@Override
public Product getResult() {
return product;
}
}
b.ConcreteBuilderB
package com.szh.pattern;
public class ConcreteBuilderB extends Builder {
private Product product = new Product();
@Override
public void BuildPartA() {
product.add("部件2.1");
}
@Override
public void BuildPartB() {
product.add("部件2.2");
}
@Override
public Product getResult() {
return product;
}
}
3)Director
package com.szh.pattern;
public class Director {
public void Construct(Builder builder){
builder.BuildPartA();
builder.BuildPartB();
}
}
4)Product
package com.szh.pattern;
import java.util.ArrayList;
import java.util.List;
public class Product {
List<String> parts = new ArrayList<String>();
public void add(String part){
parts.add(part);
}
public void show(){
System.out.print("产品创建---");
for(int i = 0; i<parts.size();i++){
System.out.print(parts.get(i));
}
}
}
5)客户端
package com.szh.pattern;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Director director = new Director();
ConcreteBuilder1 b1 = new ConcreteBuilder1();
director.Construct(b1);
Product p1 = b1.getResult();
p1.show();
ConcreteBuilder2 b2 = new ConcreteBuilder2();
director.Construct(b2);
Product p2 = b2.getResult();
p2.show();
}
}