背景

将一个复杂对象的构建与表示分离,使得同样的构建过程可以创建不同的表示。

Untitled

复杂结构

建造者(Builder)模式包含如下角色:

Untitled

上面示例是 Builder模式的常规用法,指挥者类 Director 在建造者模式中具有很重要的作用,它用于指导具体构建者如何构建产品,控制调用先后次序,并向调用者返回完整的产品类

简单结构

可以把指挥者类和抽象建造者进行结合

超级简化版:

@Data
@Builder
class House {
    private String windows;
    private String door;
    private String wall;
}

public class builder {
    public static void main(String[] args) {
        House house = House.builder()
            .wall("墙")
            .door("门")
            .windows("窗户")
            .build();

        System.out.println(house);
    }
}

原始复杂版

package builder;

class House {
    private String windows;
    private String door;
    private String wall;

    public House(Builder builder) {
        this.windows = builder.windows;
        this.door = builder.door;
        this.wall = builder.wall;
    }

    static final class Builder {
        private String windows;
        private String door;
        private String wall;

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

        public String getWindows() {
            return windows;
        }

        public Builder setWindows(String windows) {
            this.windows = windows;
            return this;
        }

        public String getDoor() {
            return door;
        }

        public Builder setDoor(String door) {
            this.door = door;
            return this;
        }

        public String getWall() {
            return wall;
        }

        public Builder setWall(String wall) {
            this.wall = wall;
            return this;
        }
    }
}

public class builder {
    public static void main(String[] args) {
        House house = new House.Builder()
            .setWall("墙")
            .setDoor("门")
            .setWindows("窗户")
            .build();

        System.out.println(house);
    }
}