将一个复杂对象的创建和它的表示分离,使得同样的创建过程可以有不同的表示。
应用场景:一水杯工厂要生产各式各样的水杯,无论杯子是神马造型,但都包括绳子,帽子和杯体。以此模型创建各种类型的杯子。
类图
cup类
public class Cup {
private String string; //绳子
private String cap; //帽子
private String cupBody; //杯体
public void setString(String string) {
this.string = string;
}
public void setCap(String cap) {
this.cap = cap;
}
public void setCupBody(String cupBody) {
this.cupBody = cupBody;
}
public void show() {
System.out.println("杯子生产完毕");
}
}
Builder类
public abstract class Builder {
protected Cup cup = new Cup();
public abstract void buildString();
public abstract void buildCap();
public abstract void buildCupBody();
public Cup getResult() {
return cup;
}
}
ClassCup类
public class ClassCup extends Builder {
@Override
public void buildString() {
cup.setString("生产绳子...");
System.out.println("生产绳子...");
}
@Override
public void buildCap() {
cup.setCap("生产帽子...");
System.out.println("生产帽子...");
}
@Override
public void buildCupBody() {
cup.setCupBody("生产杯体...");
System.out.println("生产杯体...");
}
}
Director类
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void create() {
builder.buildString();
builder.buildCap();
builder.buildCupBody();
builder.getResult().show();
}
public static void main(String[] args) {
Director d = new Director(new ClassCup());
d.create();
}
}