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

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

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

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

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

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

运行结果如下:

相关推荐
蓝瑟2 小时前
告别重复造轮子!业务组件多场景复用实战指南
前端·javascript·设计模式
Arva .4 小时前
讲一下 Spring 中用到的设计模式
java·spring·设计模式
繁华似锦respect6 小时前
lambda表达式中的循环引用问题详解
java·开发语言·c++·单例模式·设计模式·哈希算法·散列表
星月IWJ9 小时前
领域驱动设计学习
java·学习·设计模式
_dindong10 小时前
Linux网络编程:Reactor反应堆模式
linux·服务器·网络·设计模式·php
雨中飘荡的记忆10 小时前
Step Builder模式实战
java·设计模式
Eren7Y琳10 小时前
开箱即用构建应用环境:openEuler易获得性深度验证
redis·设计模式·架构
Unstoppable2211 小时前
八股训练营第 39 天 | Bean 的作用域?Bean 的生命周期?Spring 循环依赖是怎么解决的?Spring 中用到了那些设计模式?
java·spring·设计模式
闲人编程11 小时前
微服务API网关设计模式
python·缓存·微服务·设计模式·系统安全·api·codecapsule
__万波__12 小时前
二十三种设计模式(八)--装饰器模式
java·设计模式·装饰器模式