一、定义:建造者模式(builder):将一个复杂的对象构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
二、示例代码:
/*产品类*/
public class Product {
private List<String> parts = new ArrayList<String>();
public void addPart(String part) {
parts.add(part);
}
public void show() {
for (String part : parts
) {
System.out.println("产品建造过程");
System.out.println("装配:" + part);
}
}
}
/*抽象建造者类*/
public abstract class Builder {
public abstract void builderA();
public abstract void builderB();
public abstract Product getResult();
}
/*具体建造类*/
public class ConcreteBuilderA extends Builder {
private Product product = new Product();
@Override
public void builderA() {
product.addPart("part a");
}
@Override
public void builderB() {
product.addPart("part b");
}
@Override
public Product getResult() {
return product;
}
}
/*具体建造类*/
public class ConcreteBuilderB extends Builder {
private Product product = new Product();
@Override
public void builderA() {
product.addPart("part w");
}
@Override
public void builderB() {
product.addPart("part q");
}
@Override
public Product getResult() {
return product;
}
}
/*指挥者类*/
public class Director {
public void Constructor(Builder builder) {
builder.builderA();
builder.builderB();
}
}
/*客户端类*/
public class Client {
public static void main(String[] args) {
Director director = new Director();
Builder builder = new ConcreteBuilderA();
director.Constructor(builder);
Product product = builder.getResult();
product.show();
}
}