上一篇的例子中
https://blog.csdn.net/weixin_45806131/article/details/109235373
是Build模式的常规用法,Director类在Bulider模式中具有非常重要的作用,用于指导具体构建者如何构建产品,控制调用的先后顺序,并且向调用者返回完整的产品类,但是有时候需要简化系统结构,可以把Director和抽象建造者进行结合
可以通过静态内部类方式实现零件无需装配构造,这种方式更加灵活,更加符合定义
比如麦当劳的套餐,服务员(具体建造者)可以随意搭配几种产品(零件)组成一款套餐(产品),然后出售给客户,比第一种少了指挥者,将指挥权交给了用户,使得产品创建更加灵活
比如用一个点餐例子
建造者:
package bulidDemo;
//建造者
public abstract class Bulider1 {
abstract public Bulider1 builderA1(String msg); //汉堡
abstract public Bulider1 builderB1(String msg); //可乐
abstract public Bulider1 builderC1(String msg); //薯条
abstract public Bulider1 builderD1(String msg); //甜点
abstract Product1 getProduct();
}
产品:
package bulidDemo;
//产品,套餐
public class Product1 {
private String BuildA1 = "汉堡";
private String BuildB1 = "可乐";
private String BuildC1 = "薯条";
private String BuildD1 = "甜点";
public String getBuildA1() {
return BuildA1;
}
public void setBuildA1(String buildA1) {
BuildA1 = buildA1;
}
public String getBuildB1() {
return BuildB1;
}
public void setBuildB1(String buildB1) {
BuildB1 = buildB1;
}
public String getBuildC1() {
return BuildC1;
}
public void setBuildC1(String buildC1) {
BuildC1 = buildC1;
}
public String getBuildD1() {
return BuildD1;
}
public void setBuildD1(String buildD1) {
BuildD1 = buildD1;
}
@Override
public String toString() {
return "Product1{" +
"BuildA1='" + BuildA1 + '\'' +
", BuildB1='" + BuildB1 + '\'' +
", BuildC1='" + BuildC1 + '\'' +
", BuildD1='" + BuildD1 + '\'' +
'}';
}
}
服务员:
package bulidDemo;
//具体的建造者
public class Workerman extends Bulider1{
private Product1 product;
public Workerman() {
product = new Product1();
}
@Override
public Bulider1 builderA1(String msg) {
product.setBuildA1(msg);
return this;
}
@Override
public Bulider1 builderB1(String msg) {
product.setBuildB1(msg);
return this;
}
@Override
public Bulider1 builderC1(String msg) {
product.setBuildC1(msg);
return this;
}
@Override
public Bulider1 builderD1(String msg) {
product.setBuildD1(msg);
return this;
}
@Override
Product1 getProduct() {
return product;
}
}
Test测试类:
package bulidDemo;
public class Test1 {
public static void main(String[] args) {
//服务员
Workerman worker = new Workerman();
Product1 product = worker.getProduct();
System.out.println(product.toString());
//链式编程
product= worker.builderA1("全家桶").builderB1("雪碧").getProduct();
System.out.println(product.toString());
}
}
会有一个默认套餐,如果想更改,可以自己选择
优缺点:
建造者模式,产品构造和表示分离,实现解耦
可以将产品创建步骤分解在不同方法中,创建过程更倾向
具体建造者子类是相互独立的,利于系统扩展
建造者模式产品一般有很多共同点,如果产品差异较大,不适合用建造者模式
如果内部变化复杂,需要构造很多建造者
抽象工厂和建造者模式区别:
如果将抽象工厂模式比较汽车配件生产工厂,生产一个产品族的产品,建造者模式就是一个汽车组装工厂,通过对部件的组装返回完整一辆车
好了,今天先到这里~