构造器------Builder模式

Builder模式可以减少对象中构造器的创建,可以减少代码量,并且降低代码臃肿程度

1、先创建一个实例对象

    

2、然后创建对象属性

    

3、新增 Builder 内部类,并新增对象属性,对应的 set 方法以及对象的 builder() 方法

    

4、之后新增一个 对象的构造方法

    

5、如果需要求出对象的值

    可以在下面新增对应的 get 方法

    

6、看结果

    

    不需要新建很多构造方法就可以添加数据了

public class MyTest {
    private int test1;
    private int test2;
    private String test3;
    private String test4;
    public int getTest1() {
        return test1;
    }
    public int getTest2() {
        return test2;
    }
    public String getTest3() {
        return test3;
    }
    public String getTest4() {
        return test4;
    }
    public static class Builder{
        private int test1;
        private int test2;
        private String test3;
        private String test4;
        public Builder setTest1(Integer test1) {
            this.test1 = test1;
            return this;
        }
        public Builder setTest2(Integer test2) {
            this.test2 = test2;
            return this;
        }
        public Builder setTest3(String test3) {
            this.test3 = test3;
            return this;
        }
        public Builder setTest4(String test4) {
            this.test4 = test4;
            return this;
        }
        public MyTest builder() {
            return new MyTest(this);
        }
    }
    private MyTest(Builder builder){
        test1 = builder.test1;
        test2 = builder.test2;
        test3 = builder.test3;
        test4 = builder.test4;
    }
    @Override
    public String toString() {
        return "MyTest{" +
                "test1=" + test1 +
                ", test2=" + test2 +
                ", test3='" + test3 + '\'' +
                ", test4='" + test4 + '\'' +
                '}';
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值