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;
    }
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值