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

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

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

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

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

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

运行结果如下:

相关推荐
Geoking.15 小时前
【设计模式】理解单例模式:从原理到最佳实践
单例模式·设计模式
阿闽ooo17 小时前
桥接模式实战:用万能遥控器控制多品牌电视
c++·设计模式·桥接模式
驱动男孩18 小时前
22种设计模式-个人理解
设计模式
__万波__19 小时前
二十三种设计模式(十五)--访问者模式
java·设计模式·访问者模式
阿闽ooo1 天前
外观模式:从家庭电源控制看“简化接口“的设计智慧
c++·设计模式·外观模式
Geoking.1 天前
【UML】面向对象中类与类之间的关系详解
设计模式·uml
希望_睿智2 天前
实战设计模式之中介者模式
c++·设计模式·架构
有一个好名字2 天前
设计模式-观察者模式
观察者模式·设计模式
青柠代码录2 天前
【设计模式】A1-单例模式
单例模式·设计模式