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 + '\'' + '}'; } } |