Builder模式处理多个构造器

Builder模式拥有重叠构造起器的安全性和JavaBeans模式的可读性。的确,看起来代码舒服好多。当构造器参数比较多的时候推荐使用,构造器比较少的时候就不需要使用这个了。之前封装OKhttp的时候,发现Request这个类就是使用这个模式,可以借鉴一下。

这个模式其实就是构建Builder静态内部类,在Apple类的构造方法中初始化Apple对象。代码如下:

public class Apple {
    private final int a;
    private final int b;
    private final int c;
    private final int d;
    private final int e;

    public static class Builder {
        private final int a;
        private final int b;
        private int c = 0;
        private int d = 0;
        private int e = 0;

        public Builder(int a, int b) {
            this.a = a;
            this.b = b;
        }

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

        public Builder setD(int d) {
            this.d = d;
            return this;
        }

        public Builder setE(int e) {
            this.e = e;
            return this;
        }

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

    private Apple(Builder builder) {
        this.a = builder.a;
        this.b = builder.b;
        this.c = builder.c;
        this.d = builder.d;
        this.e = builder.e;
    }

    public static void main(String[] args) {
        Apple apple = new Apple.Builder(1, 1).setC(12).setD(14).build();//初始化对象
    }


}

对比一下重叠构造器:

public class MyLinearLayout {
private int a;
private int b;
private int c;
private int d;
private int e;

public MyLinearLayout() {
this(0, 0);
    }

public MyLinearLayout(int a, int b) {
this(a, b, 0);
    }

public MyLinearLayout(int a, int b, int c) {
this(a, b, c, 0);
    }

public MyLinearLayout(int a, int b, int c, int d) {
this(a, b, c, d, 0);
    }

public MyLinearLayout(int a, int b, int c, int d, int e) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
    }
}

有木有感觉可读性高了好多。

你可能感兴趣的:(Effective,java)