如果一个方法是公开的,它就不能被隐藏。您可能真正在寻找的只是一种限制访问调用方法的方法。还有其他方法可以达到类似的效果。
如果您的状态机所做的某些事情“仅在我的应用程序首次启动时使用一次”,这听起来很像那些可能在构造函数中发生的事情。尽管这取决于这些任务的复杂程度,但您可能不想在构建时这样做。
既然你说你的状态机是静态的,那它也是单例吗?您也许可以使用Singleton Pattern。
public class SimpleStateMachine {
private static SimpleStateMachine instance = new SimpleStateMachine();
private SimpleStateMachine() {
super();
System.out.println("Welcome to the machine"); // prints 1st
}
public static SimpleStateMachine getInstance() {
return instance;
}
public void doUsefulThings() {
System.out.println("Doing useful things"); // prints 3rd
}
}
下面是这个 Singleton 客户端的一些代码:
public class MachineCaller {
static SimpleStateMachine machine = SimpleStateMachine.getInstance();
public static void main(String... args) {
System.out.println("Start at the very beginning"); // prints 2nd
machine.doUsefulThings();
}
}
请注意,SimpleStateMachine 实例直到您的类第一次被访问时才会构建。因为它在MachineCaller 客户端中声明为static,所以算作“首次访问”并创建实例。如果您确实希望您的状态机在应用程序启动时执行其中一些初始化任务,请记住这一点。
因此,如果您不想将状态机类变成真正的单例...您可以在第一次访问该类时使用static initialization block 执行一次性任务。看起来像这样:
public class SimpleStateMachine {
static {
System.out.println("First time tasks #1");
System.out.println("First time tasks #2");
}
public SimpleStateMachine() {
super();
System.out.println("Welcome to the machine");
}
public void doUsefulThings() {
System.out.println("Doing useful things");
}
}
当我们讨论它时,既然你提到它是一个状态机......Head First Design Patterns 这本书对State Pattern 做了一个很好的、易于理解的处理。如果您还没有,我建议您阅读它。