1.建造者模式Builder:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
2.类图:
3.代码:
组装PC:
1.Diretor和Client需求沟通 ; 2.各个部件Builder
3.ConcreteBuilder去构建组件; 4.成品Product
public abstract class Builder {
//1.CPU
public abstract void buildCPU();
//2.MainBoard
public abstract void buildMainBoard();
//3.HD
public abstract void buildHD();
//4.返回成品
public abstract Product getProduct();
}
public class ConcreteBuilder extends Builder {
//创建产品实例
Product product = new Product();
//组装
@Override
public void buildCPU() {
product.add("CPU");
}
@Override
public void buildMainBoard() {
product.add("MianBoard");
}
@Override
public void buildHD() {
product.add("HD");
}
//返回组装完成的Product
@Override
public Product getProduct() {
return product;
}
}
public class Director {
//指挥组装
public void construct(Builder builder) {
builder.buildCPU();
builder.buildMainBoard();
builder.buildHD();
}
}
import java.util.List;
import java.util.ArrayList;
public class Product {
//产品组件集合
private List<String> parts = new ArrayList<String>();
//组装
public void add(String part) {
parts.add(part);
}
public void print() {
for (int i = 0; i < parts.size(); i++) {
System.out.println("组件" + parts.get(i) + "安装完毕");
}
}
}
public class Client {
public static void main(String[] args) {
Director director = new Director();
Builder concreteBuilder = new ConcreteBuilder();
director.construct(concreteBuilder);
Product product = concreteBuilder.getProduct();
product.print();
}
}
版权声明:本文为zhangfcu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。