如何标记方法必须?

uzi*_*lan 9 java annotations design-patterns builder

假设你创建一个使用生成器模式的人一个类名,并假设生成器类包含的方法body(),head(),arms()当然build(),你考虑的方法head(),并build()为这个类的用户必须的.

我们想以某种方式标记这些方法是强制性的,如果可能的话使用注释.如果这个类的用户试图构建一个Person实例但是忘了调用这些方法中的任何一个,我们希望得到某种警告 - 无论是来自java编译器,还是来自我们用来构建我们的Eclipse或Maven项目 - 他们中的任何一个都可以.

有可能吗?你会建议哪种方式?

pgr*_*ras 21

下面是一个使用不同类型来强制某些部分的示例(它还使您调用方法的顺序成为必需的):

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


编辑

OP对这个答案留下了深刻的印象,他在博客中完整地写了这篇文章.这是对建造者模式的一种巧妙的看法,这里应该引用完整的处理方法.