建造者模式(Builder),将一个复杂对象的构建(Add)与它的表示(p1.Show()和p2.Show())分离,使得同样的构建过程(指construct方法)可以创建不同的表示。
主方法,客户端不需要知道具体建造过程
public class main {
public static void main(String[] args) {
Director director = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
director.Construct(b1);//指挥者用ConcreteBuilder的方法来建造产品
Product p1 = b1.GetResult();
p1.Show();
director.Construct(b2);
Product p2 = b2.GetResult();
p2.Show();
}
}
产品类
import java.util.ArrayList;
import java.util.List;
/**
* 产品类,由多个部件组成,存放于list当中
*/
public class Product {
List<String> parts = new ArrayList<String>();
public void Add(String part) {//添加产品部件
parts.add(part);
}
public void Show() {//列举所有产品部件
System.out.println("\n 产品 创建 ----");
for (String part: parts) {
System.out.println(part);
}
}
}
抽象建造类
public abstract class Builder {
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product GetResult();
}
具体构造类1
public class ConcreteBuilder1 extends Builder {
private Product product = new Product();
//建造具体的两个部件是部件A和部件B
public void BuildPartA() {
product.Add("部件A");
}
public void BuildPartB() {
product.Add("部件B");
}
public Product GetResult() {
return product;
}
}
具体构造类2
public class ConcreteBuilder2 extends Builder {
private Product product = new Product();
//建造具体的两个部件是部件X和部件Y
public void BuildPartA() {
product.Add("部件X");
}
public void BuildPartB() {
product.Add("部件Y");
}
public Product GetResult() {
return product;
}
}
指挥者类,把所有构建相关的方法写到这个类里面
/**
* 用来指挥建造过程
*/
public class Director {
public void Construct(Builder builder) {
builder.BuildPartA();
builder.BuildPartB();
}
}