建造者模式 Builder Pattern

2020-11-06 13:16:50 浏览数 (1)

Builder Pattern,是 Java 常用的设计模式之一。它提供了一种将多个简单对象一步步构建成一个复杂对象的能力。

它的结构

  • 产品角色,复杂的产品实例。
  • 抽象建造者角色,与业务逻辑无关,是具体建造者角色必须实现的接口或继承的父类。(可省略)
  • 具体建造者角色,具体构成某一复杂对象的类。

一个简单的演示

演示代码

代码语言:javascript复制
// 产品类
public class Phone {
    private String name;
    private String screen;
    private String cpu;
    private String capacity;
    public Phone() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getScreen() {
        return screen;
    }
    public void setScreen(String screen) {
        this.screen = screen;
    }
    public String getCpu() {
        return cpu;
    }
    public void setCpu(String cpu) {
        this.cpu = cpu;
    }
    public String getCapacity() {
        return capacity;
    }
    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }
    @Override
    public String toString() {
        return String.format("Phone(name: %s,screen: %s,cpu: %s, capacity: %s)",
                this.name, this.screen, this.cpu, this.capacity);
    }
}
// 建造者
public class PhoneBuilder {
    private Phone phone;
    public PhoneBuilder() {
        this.phone = new Phone();
    }
    public PhoneBuilder setName(String name) {
        phone.setName(name);
        return this;
    }
    public PhoneBuilder setScreen(String screen) {
        phone.setScreen(screen);
        return this;
    }
    public PhoneBuilder setCpu(String cpu) {
        phone.setCpu(cpu);
        return this;
    }
    public PhoneBuilder setCapacity(String capacity) {
        phone.setCapacity(capacity);
        return this;
    }
    public Phone build() {
        return phone;
    }
}
// 测试类
public class PhoneBuilderTest {
    @org.junit.Test
    public void phone() {
        Phone phone12 = new PhoneBuilder()
                .setName("iphone 12")
                .setScreen("6.1 英寸 (对角线) OLED 全面屏")
                .setCpu("A14 仿生芯片")
                .setCapacity("256GB")
                .build();
        System.out.println(phone12.toString());

        Phone phoneXS = new PhoneBuilder()
                .setName("iphone XS")
                .setScreen("5.8 英寸 (对角线) OLED 全面屏")
                .setCpu("A12 仿生芯片")
                .setCapacity("256GB")
                .build();
        System.out.println(phoneXS.toString());
    }
}

运行结果

总结

建造者模式是一种简单容易理解的设计模式。它在实际的开发中,经常运用于复杂对象的构建工作。

0 人点赞