「软件工程-设计模式」 建造者模式

Posted by Dawn-K's Blog on February 21, 2021

建造者模式

知乎参考资料

概述

当一个类特别复杂时(比如构造函数有很多参数且有一些可选参数), 考虑建造者模式.

建造者模式的一种简单实现是使用建造者类通过一系列set的链式调用来构建一个复杂的对象.

比如电脑, 其有多个必选属性, 也有一些可选属性. 由于Java本身不支持默认参数, 导致构建很复杂(可以使用重叠构造器, 但是也不够优雅).

实现方法

我们将 Computer 的构造函数变为私有, 然后写一个 public 的内部类 Builder, 其与 Computer 有相同的成员, 并且有对应的 setter, 然后有一个 build(), 用来构造出真正的 Computer.

之所以大费周章的采用这种方式, 而不是 Computer直接写 setter是因为这个 Computer 想设置为一个不可变对象, 也就是一旦被生产出来, 其属性就不可更改.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Computer {
    private final String cpu;//必须
    private final String ram;//必须
    private final int usbCount;//可选
    private final String keyboard;//可选
    private final String display;//可选

    private Computer(Builder builder){
        this.cpu=builder.cpu;
        this.ram=builder.ram;
        this.usbCount=builder.usbCount;
        this.keyboard=builder.keyboard;
        this.display=builder.display;
    }
    public static class Builder{
        private String cpu;//必须
        private String ram;//必须
        private int usbCount;//可选
        private String keyboard;//可选
        private String display;//可选

        public Builder(String cup,String ram){
            this.cpu=cup;
            this.ram=ram;
        }

        public Builder setUsbCount(int usbCount) {
            this.usbCount = usbCount;
            return this;
        }
        public Builder setKeyboard(String keyboard) {
            this.keyboard = keyboard;
            return this;
        }
        public Builder setDisplay(String display) {
            this.display = display;
            return this;
        }        
        public Computer build(){
            return new Computer(this);
        }
    }
  //省略getter方法
}

构建电脑类对象时, 只需要链式调用即可.

1
2
3
4
5
Computer computer=new Computer.Builder("因特尔","三星")
                .setDisplay("三星24寸")
                .setKeyboard("罗技")
                .setUsbCount(2)
                .build();