1.适用场景:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。如果我们用了建造者模式,那么用户程序就只需要指定要建造的类型就可以得到它们,而具体建造的过程和细节就不需要知道了。
2.定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
3.UML类图
4.简单代码实现:
package com.guo.builderPattern;
import java.util.ArrayList;
import java.util.List;
public class Product {
private List<String> parts = new ArrayList<>();
public void add(String part){
parts.add(part);
}
public void show(){
System.out.println("产品 创建。。。");
for (String part : parts) {
System.out.println(part);
}
}
}
package com.guo.builderPattern;
public interface Builder {
void buildPartA();
void buildPartB();
Product getResult();
}
package com.guo.builderPattern;
public class ConcreteBuilder1 implements 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;
}
}
package com.guo.builderPattern;
public class ConcreteBuilder2 implements 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;
}
}
package com.guo.builderPattern;
public class Director {
public void construct(Builder builder) {
builder.buildPartA();
builder.buildPartB();
}
}
package com.guo.builderPattern;
public class BuilderClient {
public static void main(String[] args) {
Director director = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
//在指挥者方法中来确定构建顺序
director.construct(b1);
//从不同的构建者获得构建的不同产品
Product result = b1.getResult();
result.show();
director.construct(b2);
Product result2 = b2.getResult();
result2.show();
}
}