【发布时间】:2012-01-18 23:15:09
【问题描述】:
我有
public enum BaseActions implements Actions{
STAND (0,0,0),
TURN (1,1,1);
//other stuff
}
public enum CoolActions implements Actions{
STAND (0,2,3),
TURN(1,6,9);
//other stuff
}
public enum LooserActions implements Actions{
STAND (0,-2,-3),
TURN(1,-6,-9);
//other stuff
}
public interface Actions {
//interface methods
}
class A {
Actions mCurrentAction;
protected void notifyNewAction(final Actions pAction, final Directions pDirection){
//body of the method
}
public void doStuff(final Actions pAction) {
if(pAction.getMyId() > 0)
notifyNewAction(BaseActions.STAND, myDirection);
else
notifyNewAction(BaseActions.TURN, myDirection);
}
}
class B extends A{
public void doMyStuff() {
doStuff(CoolActions.STAND);
}
}
class C extends A{
public void doMyStuff() {
doStuff(LooserActions.STAND);
}
}
我想让 A 在从 B 调用 doStuff 时使用 CoolActions 在从 C 调用时使用 LooserActions。 我认为我可以做到的一种方法是使用泛型,然后在 B 和 C 中使用
doStuff<CoolActions>(CoolActions.STAND)
并且在A中拥有
public void doStuff<T extends EnumActions&Actions>(final Actions pAction) {
if(pAction.getMyId() > 0)
notifyNewAction(T.STAND, myDirection);
else
notifyNewAction(T.TURN, myDirection);
}
其中 EnumActions 是一个基本枚举,它只包含枚举元素的声明,仅此而已,类似于枚举的接口,但枚举不能扩展另一个类,因为它们已经扩展了 Enum,而接口不能提供我的意思。 另一种方法是让枚举实现一个 EnumActions 接口,该接口具有
public interface EnumActions {
public <T> T getStand();
public <T> T getTurn();
}
并且拥有
class A {
Actions mCurrentAction;
protected void notifyNewAction(final Actions pAction, final Directions pDirection){
//body of the method
}
public <T implements EnumActions> void doStuff(final Actions pAction) {
if(pAction.getMyId() > 0)
notifyNewAction(T.getStand(), myDirection);
else
notifyNewAction(T.getTrun(), myDirection);
}
}
和
public enum CoolActions implements Actions, EnumActions{
STAND (0,2,3),
TURN(1,6,9);
public CoolActions getStand();
public CoolActions getTurn();
//other stuff
}
class B extends A{
public void doMyStuff() {
doStuff<CoolActions>(CoolActions.STAND);
}
}
但是 1)我不知道它是否会起作用 2)我失去了使用枚举的优势 3)这接缝是处理这个问题的非常糟糕的方法 4)我必须写很多(每个 Y X 枚举字段不同的枚举)。我从静态最终字段更改为枚举以提高可读性和顺序,而这使事情变得更加困难。
我是否以错误的方式设计了这个?我该如何处理? 有解决此问题的首选方法吗? 谢谢
【问题讨论】:
标签: java class inheritance enums