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

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

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

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

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

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

运行结果如下:

相关推荐
数据智能老司机12 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机13 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴16 小时前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
李广坤16 小时前
工厂模式
设计模式
幂简集成explinks2 天前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
努力也学不会java2 天前
【设计模式】抽象工厂模式
java·设计模式·oracle·抽象工厂模式
青草地溪水旁2 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁2 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
Magnetic_h2 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa