如何标记一个方法是强制性的?
假设您使用 builder 模式创建了一个名为 Person 的类,并假设 Builder 类包含方法 body()
、head()
、arms()
当然还有 build()
并且你认为方法 head()
和 build()
对于这个类的用户来说是必须的.
Suppose you create a class names Person using the builder pattern, and suppose the Builder class contains methods body()
, head()
, arms()
and of course build()
and you consider methods head()
and build()
obligatory for the user of this class.
我们希望以某种方式将这些方法标记为强制性,如果可能的话,使用注释.如果这个类的用户试图构建一个 Person 实例但忘记调用这些方法中的任何一个,我们希望得到某种警告 - 来自 java 编译器,或者可能来自我们用来构建我们的 Eclipse 或 Maven项目 - 他们中的任何一个都可以.
We would like to somehow mark these methods obligatory, if possible using annotations. If a user of this class tries to build a Person instance but forgot to call either of these methods, we would like to get some kind of warning - either from the java compiler, or maybe from Eclipse or Maven, which we use to build our projects - any of them would do.
有可能吗?你会建议哪种方式?
Is it possible to do? Which way would you suggest?
推荐答案
这是一个使用不同类型强制某些部分的示例(它也强制调用方法的顺序):
Here is an example with using different types to make some parts mandatory (it also makes the order you call the methods mandatory):
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 对这个答案印象深刻,他将其完整地写在 博客.这是对构建器模式的巧妙理解,值得在这里引用完整的处理方法.
The OP was so impressed with this answer that he wrote it up fully in a blog. It's such a clever take on the builder pattern that a full treatment deserves to be referenced here.
相关文章