Builder 模式 Java 實現

Builder 模式允許你以易於閱讀的方式建立具有許多可選變數的類的例項。

請考慮以下程式碼:

public class Computer {

    public GraphicsCard graphicsCard;
    public Monitor[] monitors;
    public Processor processor;
    public Memory[] ram;
    //more class variables here...

    Computer(GraphicsCard g, Monitor[] m, Processer p, Memory ram) {
        //code omitted for brevity...
    }

    //class methods omitted...

}

如果所有引數都是必要的,這一切都很好。如果有更多變數和/或其中一些是可選的怎麼辦?你不希望使用必需引數和可選引數的每種可能組合來建立大量建構函式,因為它很難維護並且開發人員難以理解。你也可能不希望有一個很長的引數列表,其中許多引數可能需要由使用者輸入為 null。

Builder 模式建立一個名為 Builder 的內部類,用於僅例項化所需的可選變數。這是通過每個可選變數的方法完成的,該變數將變數型別作為引數並返回 Builder 物件,以便方法可以相互連結。任何必需的變數都放在 Builder 建構函式中,這樣就不會遺漏它們。

Builder 還包含一個名為 build() 的方法,它返回它所在的物件,並且在構建物件時必須在方法呼叫鏈的末尾呼叫。

從前面的示例開始,此程式碼使用 Builder 類的 Computer 模式。

public class Computer {

    private GraphicsCard graphicsCard;
    private Monitor[] monitors;
    private Processor processor;
    private Memory[] ram;
    //more class variables here...

    private Computer(Builder builder) {
        this.graphicsCard = builder.graphicsCard;
        this.monitors = builder.monitors;
        this.processor = builder.processor;
        this.ram = builder.ram;
    }

    public GraphicsCard getGraphicsCard() {
        return this.graphicsCard;
    }

    public Monitor[] getMonitors() {
        return this.monitors;
    }

    public Processor getProcessor() {
        return this.processor;
    }

    public Memory[] getRam() {
        return this.ram;
    }

    public static class Builder {
        private GraphicsCard graphicsCard;
        private Monitor[] monitors;
        private Processor processor;
        private Memory[] ram;

        public Builder(Processor p){
            this.processor = p;
        }

        public Builder graphicsCard(GraphicsCard g) {
            this.graphicsCard = g;
            return this;
        }

        public Builder monitors(Monitor[] mg) {
            this.monitors = mg;
            return this;
        }

        public Builder ram(Memory[] ram) {
            this.ram = ram;
            return this;
        }

        public Computer build() {
            return new Computer(this);
        }
    }
}

如何使用此類的示例:

public class ComputerExample {

    public static void main(String[] args) {
        Computer headlessComputer = new Computer.Builder(new Processor("Intel-i3"))
                .graphicsCard(new GraphicsCard("GTX-960"))
                .build();

        Computer gamingPC = new Computer.Builder(new Processor("Intel-i7-quadcode"))
                .graphicsCard(new GraphicsCard("DX11"))
                .monitors(new Monitor[] = {new Monitor("acer-s7"), new Monitor("acer-s7")})
                .ram(new Memory[] = {new Memory("2GB"), new Memory("2GB"), new Memory("2GB"), new Memory("2GB")})
                .build();
    }

}

此示例顯示了構建器模式如何在很少的工作量的情況下為類的建立提供了很大的靈活性。計算機物件可以基於呼叫者期望的配置以易於閱讀的方式實現而不費力。