设计模式之建造者模式精讲

也叫生成器模式。将一个复杂的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

在建造者模式中,有如下4个角色:

  • 抽象建造者(Builder):用于规范产品的各个组成部分,并进行抽象,一般独立于应用程序的逻辑。
  • 具体建造者(Concrete Builder):实现抽象建造者的所有方法,并返回一个组建好的产品实例(Product)。
  • 产品(Product):建造中的对象,一个系统会有多于一个的产品类,这些产品不一定有共同的接口,可以是不相关的。
  • 导演(Director):该角色负责安排已有模块的顺序,指导Builder的建造过程,可以有多个Director角色。

我们通过一个生产不同品牌电脑的例子来加深理解:

java 复制代码
public abstract class Computer {
    protected String cpu;
    protected String band;
    public abstract void assemble();
}

public class DellComputer extends Computer {
    @Override
    public void assemble() {
        this.band = "Dell";
    }
}

public class HpComputer extends Computer {
    @Override
    public void assemble() {
        this.band = "Hp";
    }
}

public abstract class AbstractBuilder {
    protected Computer computer;
    public abstract void setCpu();
    public abstract Computer build();
}

public class DellBuilder extends AbstractBuilder {
    public DellBuilder() {
        this.computer = new DellComputer();
    }
    @Override
    public void setCpu() {
        this.computer.cpu = "intel";
    }
    @Override
    public Computer build() {
        this.computer.assemble();
        return this.computer;
    }
}

public class HpBuilder extends AbstractBuilder {
    public HpBuilder() {
        this.computer = new HpComputer();
    }
    @Override
    public void setCpu() {
        this.computer.cpu = "intel";
    }
    @Override
    public Computer build() {
        this.computer.assemble();
        return this.computer;
    }
}

public class Director {
    private AbstractBuilder builder;
    public Director(AbstractBuilder builder) {
        this.builder = builder;
    }
    public Computer create() {
        builder.setCpu();
        return builder.build();
    }
}

大家如果需要视频版本的讲解,可以关注下我的B站:

五、设计模式之建造者模式精讲

相关推荐
恋红尘5 小时前
设计模式详解
设计模式
Code_Geo8 小时前
agent设计模式:第一章节—提示链
microsoft·设计模式·agent·模型
懂得节能嘛.12 小时前
【设计模式】Java规则树重构复杂业务逻辑
java·开发语言·设计模式
tan77º12 小时前
【项目】基于多设计模式下的同步&异步日志系统 - 项目介绍与前置知识
linux·c++·设计模式
Query*1 天前
Java 设计模式——工厂模式:从原理到实战的系统指南
java·python·设计模式
庸了个白1 天前
一种面向 AIoT 定制化场景的服务架构设计方案
mqtt·设计模式·系统架构·aiot·物联网平台·动态配置·解耦设计
Meteors.1 天前
23种设计模式——访问者模式 (Visitor Pattern)
设计模式·访问者模式
Vallelonga1 天前
Rust 设计模式 Marker Trait + Blanket Implementation
开发语言·设计模式·rust
en-route1 天前
设计模式的底层原理——解耦
设计模式
杯莫停丶1 天前
设计模式之:工厂方法模式
设计模式·工厂方法模式