假设您使用构建器模式创建一个名为 Person 的类,并假设该 Builder 类包含方法body()
, head()
, arms()
而且当然build()
然后你考虑方法head()
and build()
该类的用户必须这样做。
我们希望以某种方式将这些方法标记为必需的,如果可能的话使用注释。如果此类的用户尝试构建 Person 实例,但忘记调用这些方法中的任何一个,我们希望收到某种警告 - 要么来自 java 编译器,要么来自 Eclipse 或 Maven,我们用它们来构建我们的实例。项目——任何一个都可以。
可以做吗?你会建议哪种方式?
下面是一个使用不同类型使某些部分成为强制性的示例(它也使您调用方法的顺序成为强制性的):
package test;
import test.StepOne.StepThree;
import test.StepOne.StepTwo;
import test.StepOne.LastStep;
public class TestBuilder {
public static void main(String[] args) {
String person1 = PersonBuilder.newInstance().head("head").body("body").arm("arm").leg("leg").build();
String person2 = PersonBuilder.newInstance().head("head").body("body").arm("arm").build();
}
}
interface StepOne {
// mandatory
StepTwo head(String head);
interface StepTwo {
// mandatory
StepThree body(String body);
}
interface StepThree {
// mandatory
LastStep arm(String arm);
}
// all methods in this interface are not mandatory
interface LastStep {
LastStep leg(String leg);
String build();
}
}
class PersonBuilder implements StepOne, StepTwo, StepThree, LastStep {
String head;
String body;
String arm;
String leg;
static StepOne newInstance() {
return new PersonBuilder();
}
private PersonBuilder() {
}
public StepTwo head(String head) {
this.head = head;
return this;
}
public LastStep arm(String arm) {
this.arm = arm;
return this;
}
public StepThree body(String body) {
this.body = body;
return this;
}
public LastStep leg(String leg) {
this.leg = leg;
return this;
}
public String build() {
return head + body + arm + leg;
}
}
Edit
OP 对这个答案印象深刻,因此他将其完整地写在了 blog。这是对构建器模式的巧妙采用,值得在这里引用完整的处理方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)