对建造者模式理解

当对象成员变量太多时,使用建造方法给变量赋值往往变得很臃肿,所以可以这样做

public class Something {

    private String a;
    private String b;
    private String c;
    private String d;
    private String e;

    public Something(Builder builder) {
        this.a = builder.a;
        this.b = builder.b;
        this.c = builder.c;
        this.d = builder.d;
        this.e = builder.e;
    }

    static class Builder{
        private String a;
        private String b;
        private String c;
        private String d;
        private String e;

        public Builder setA(String a) {
            this.a = a;
            return this;
        }

        public Builder setB(String b) {
            this.b = b;
            return this;
        }

        public Builder setC(String c) {
            this.c = c;
            return this;
        }

        public Builder setD(String d) {
            this.d = d;
            return this;
        }
        public Builder setE(String e) {
            this.e = e;
            return this;
        }

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

    public static void main(String[] args) {
        Something something = new Something.Builder().setA("a").setB("b").
                setC("c").setD("d").setE("e").build();
        System.out.println(something.a);
    }

对传统建造者模式的理解

传统建造者模式,可以将实体类中的部分属性抽象出来并单独建造,并且实体的构建过程交予构造者。我认为这是外观模式和策略模式的结合。

关于传统建造者模式可以看如下文章

秒懂设计模式之建造者模式(Builder pattern) - shusheng007的文章 - 知乎

你可能感兴趣的:(建造者模式,java,前端)