所以我有一个对象,让我们称之为myObject
这是我对象的构造函数
private static class myObject {
public myObject(int argA) {
this.argA = argA;
}
public myObject(int argA, boolean argB) {
this.argA = argA;
this.argB = argB;
}
public myObject(int argA, int argC, int argD) {
this.argA = argA;
this.argC = argC;
this.argD = argD;
}
public myObject(int argA, String argE) {
this.argA = argA;
this.argE = argE;
}
public int argA = 1;
public boolean argB;
public int argC = 4;
public int argD = 5;
public String argE;
基本上,我有默认值,构造函数在需要时会覆盖这些默认值。 当我调用这些构造函数时,这使得代码非常干净
myObject newObject = new myObject(4);
但是,API给我一个参数列表,用于创建带有
List objectParams1 = Arrays.asList(1,3,4)
List objectParams2 = Arrays.asList(1,false)
List objectParams3 = Arrays.asList(1,"tomato")
myObject newObjectWithTheseParameters1 = ?;
myObject newObjectWithTheseParameters2 = ?;
myObject newObjectWithTheseParameters3 = ?;
使用参数列表创建该对象非常困难,因为它不知道要使用哪个构造函数。生成器方法是解决这个问题的方法吗?但是,这将使代码库更大,因为我不得不将此构造函数调用〜100次。
myObject objectA = myObject.builder().withargA(4).withArgB(true).build();