建造者模式
产品
import java.util.ArrayList;
import java.util.List;
public class Product {
private List<String> list = new ArrayList<>();
public void add(String part) {
list.add(part);
}
public void show() {
for (String s : list) {
System.out.println(s);
}
}
}
抽象的建造者
public abstract class Builder {
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product getResult();
}
具体的两个建造者
public class ConcreteBuilder_1 extends Builder {
private Product product = new Product();
@Override
public void BuildPartA() {
product.add("部件A");
}
@Override
public void BuildPartB() {
product.add("部件B");
}
@Override
public Product getResult() {
return product;
}
}
public class ConcreteBuilder_2 extends Builder {
private Product product = new Product();
@Override
public void BuildPartA() {
product.add("部件X");
}
@Override
public void BuildPartB() {
product.add("部件Y");
}
@Override
public Product getResult() {
return product;
}
}
指挥者
public class Director {
public void Construct(Builder builder) {
builder.BuildPartA();
builder.BuildPartB();
}
}
测试
public class Main {
public static void main(String[] args) {
Director director = new Director();
Builder builder1 = new ConcreteBuilder_1();
Builder builder2 = new ConcreteBuilder_2();
director.Construct(builder1);
Product product1 = builder1.getResult();
product1.show();
director.Construct(builder2);
Product product2 = builder2.getResult();
product2.show();
}
}