我想要存储在枚举类上,所以以后我可以实例化这个类。但我不知道我怎么能做到。
这就是一个例子:
public enum STATE {
MENU(Menu.class, Color bgColor);
PLAY(Play.class, Color bgColor);
...
public 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中这样做。
发布于 2016-02-17 09:50:31
我建议在这个枚举中使用抽象的工厂方法。
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();
}我省略了颜色字段,因为它不清楚它应该如何使用。如果每个状态的颜色相同,则可以将其作为额外的私有字段添加到枚举中。如果在构造新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();
}
}https://stackoverflow.com/questions/35452778
复制相似问题