下面是使用不同類型做出一些地方強制爲例(它也會讓你叫強制方法的順序排列):
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;
}
}
編輯
的OP是如此這個答案給他留下了深刻的印象,他完全在 blog中寫下了這個答案。這是一個聰明的建設者模式,完整的治療值得引用這裏。
懷疑你可以在編譯時做到這一點,除非*非常*特殊情況。在運行時應該很容易地進行這樣的檢查(儘管我一直這樣做)。 – NPE 2012-02-03 09:22:48
我無法想象一種方法來做到這一點,然後將強制屬性作爲參數添加到構建器構造函數中,或者在調用'build'時拋出異常,但我很好奇如果有人有更好的主意。 – 2012-02-03 09:24:11