我想存储在一个枚举类上,这样以后我就可以实例化这个类。但我不知道我该怎么做。
这是一个例子:
public enum STATE {
MENU(Menu.class, Color bgColor);
PLAY(Play.class, Color bgColor);
...
public STATE() {...
}
}
并且有一种在状态之间改变的方法。 STATE 上的所有类都继承自 AState,例如 (public class Menu extends AState{...}
)
Astate currentState;
public void changeState(STATE s){
if(currentState != null) currentState.dispose();
currentState = ...some code to instantiate the class and assign to this value
currentState.init();
}
我的想法是有一个枚举来保存每个状态的类,以及一些参数来用不同的值实例化这个类,比如他的 bgColor,但我不知道如何在 Java 中做到这一点。
最佳答案
我建议在此枚举中使用抽象工厂方法。
public enum State {
MENU {
public AState createInstance() { return new Menu();}
},
PLAY {
public AState createInstance() { return new Play();}
};
public abstract AState createInstance();
}
那么你可以这样做:
public void changeState(State s){
if(currentState != null) currentState.dispose();
currentState = s.createInstance();
}
我省略了颜色字段,因为不清楚应该如何使用它。如果每个州的颜色都相同,则可以将其作为额外的私有(private)字段添加到枚举中。如果在构造新的 AState
实例时使用各种颜色,它可以作为参数传递给 createInstance()
方法。
如果你使用 Java 8,这个枚举可以用更优雅的方式编写:
public enum State {
MENU(Menu::new),
PLAY(Play::new);
Supplier<AState> stateConstructor;
State(Supplier<AState> constructor) {
stateConstructor = constructor;
}
public AState createInstance() {
return stateConstructor.get();
}
}
关于java - 创建一个知道他的类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452778/