设计模式—创建型模式之建造者模式

设计模式---创建型模式之建造者模式

如果我们创建的对象比较复杂,但其细节还要暴露给使用者,这样就需要用到建造者模式。

建造者设计模式,屏蔽过程,而不屏蔽细节。

比如我们有一个手机类,定义如下:

java 复制代码
public class Phone {
    //cpu
    private String cpu;
    //运行内存
    private String memory;
    //存储内存
    private String disk;
    //省略getter and setter 省略toString
}

我们想定制自己的一个手机,可以先定义一个抽象的构建者;

java 复制代码
public abstract class AbstarctPhoneBuilder {
    Phone phone;
    //定制cpu
    abstract AbstarctPhoneBuilder withCpu(String cpu);
    //定制运行内存
    abstract AbstarctPhoneBuilder withMemory(String memory);
    //定制存储内存
    abstract AbstarctPhoneBuilder withDisk(String disk);
    //返回构建好的phone
    Phone build(){
        return phone;
    }
}

如果我们想定制一个香蕉手机,就可以继承这个抽象的构建者,然后实现这些定制方法:

java 复制代码
public class BananaPhoneBuilder extends AbstarctPhoneBuilder{

    public BananaPhoneBuilder(){
        this.phone = new Phone();
    }

    @Override
    AbstarctPhoneBuilder withCpu(String cpu) {
        this.phone.setCpu(cpu);
        return this;
    }

    @Override
    AbstarctPhoneBuilder withMemory(String memory) {
        this.phone.setMemory(memory);
        return this;
    }

    @Override
    AbstarctPhoneBuilder withDisk(String disk) {
        this.phone.setDisk(disk);
        return this;
    }
}

使用方式如下:

java 复制代码
public class BuilderTest {
    public static void main(String[] args) {
        AbstarctPhoneBuilder builder = new BananaPhoneBuilder();
        Phone phone = builder.withCpu("量子cpu")
                .withMemory("1T运行内存")
                .withDisk("100T存储内存")
                .build();
        System.out.println(phone.toString());
    }
}

运行结果如下:

相关推荐
Yu_Lijing3 小时前
基于C++的《Head First设计模式》笔记——模式合作
c++·笔记·设计模式
S-X-S3 小时前
常用设计模式+集成websocket
websocket·设计模式
编程饭碗7 小时前
【二十三种设计模式】
设计模式
茶本无香14 小时前
设计模式之五—门面模式:简化复杂系统的统一接口
java·设计模式
小码过河.15 小时前
设计模式——模板方法模式
python·设计模式·模板方法模式
Engineer邓祥浩15 小时前
设计模式学习(19) 23-17 观察者模式
学习·观察者模式·设计模式
一条闲鱼_mytube16 小时前
智能体设计模式(六)资源感知优化-推理技术-评估与监控
网络·人工智能·设计模式
一条闲鱼_mytube16 小时前
智能体设计模式(七)优先级排序-探索与发现
网络·人工智能·设计模式
羞儿1 天前
Agent设计模式与工程化
设计模式·知识图谱·agent·rag·mcp·指导开发
点云SLAM1 天前
C++(C++17/20)最佳工厂写法和SLAM应用综合示例
开发语言·c++·设计模式·c++实战·注册工厂模式·c++大工程系统