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

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

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

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

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

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());
    }
}

运行结果如下:

相关推荐
怕浪猫11 小时前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane199413 小时前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19942 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..2 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1502 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)3 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki3 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅663 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa4 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio
sarasuki4 天前
如何让 Agent 获取更多的能力?插件 / 技能系统
人工智能·设计模式·agent