- 建造者模式也属于创建型模式,它提供了一种创建对象的最优方式
- 定义:将一个复杂对象的构建与它的表示分离,使得同样的构建可以创建不同的表示
- 主要作用,在用户不知道对象的建造过程和细节的情况下直接创建复杂的对象
- 例子
- 工厂(建造者模式):负责制造汽车
- 汽车购买者:只需要告知型号(对象的类型和内容),然后可以直接使用了。
- 我觉得可以配合抽象工厂模式,将对象的创建完成封闭
建造者模式示例
##创建一个产品模型
public class Product {
private String buildA = "可乐";
private String buildB = "汉堡";
private String buildC = "炸鸡";
public String getBuildA() {
return buildA;
}
public void setBuildA(String buildA) {
this.buildA = buildA;
}
public String getBuildB() {
return buildB;
}
public void setBuildB(String buildB) {
this.buildB = buildB;
}
public String getBuildC() {
return buildC;
}
public void setBuildC(String buildC) {
this.buildC = buildC;
}
@Override
public String toString() {
return "Product{" +
"buildA='" + buildA + '\'' +
", buildB='" + buildB + '\'' +
", buildC='" + buildC + '\'' +
'}';
}
}
public abstract class Builder {
abstract Builder buildA(String msg);
abstract Builder buildB(String msg);
abstract Builder buildC(String msg);
abstract Product getProduct();
}
##创建具体的制造产品的工人
public class Worker extends Builder {
private Product product;
public Worker() {
this.product = new Product();
}
@Override
Builder buildA(String msg) {
product.setBuildA(msg);
return this;
}
@Override
Builder buildB(String msg) {
product.setBuildB(msg);
return this;
}
@Override
Builder buildC(String msg) {
product.setBuildB(msg);
return this;
}
@Override
Product getProduct() {
return this.product;
}
}
#测试
public static void main(String[] args) {
Product product = new Worker().buildA("吮指原味鸡").getProduct();
System.out.println(product);
}