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);
}
}
我想提出时doStuff从B和LooserActions称为A使用CoolActions从C 叫的方式之一时使用的枚举我认为我可以做到这一点是使用泛型,然后在B和C使用
doStuff<CoolActions>(CoolActions.STAND)
,并已在
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元素声明的基本枚举,仅此而已,类似于枚举接口,但枚举不能扩展另一个类,因为它们已经扩展Enum,并且接口不能提供什么我的意思是。 另一种方法是使枚举实现了具有
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)我不知道是否会一EnumActions接口工作2)我失去了使用枚举的优点3)这接近了一个非常糟糕的方式来处理这个4)我将不得不写很多(X枚举字段每Y不同的枚举)。我从静态最终字段改为枚举以提高可读性和顺序,并且这种接合使事情变得更加困难。
我的设计方式错了吗?我该如何处理? 是否有解决此问题的首选方法? 谢谢
那么,什么是如果他们可以通过类来代替,不能做什么,他们是专为(限的选择有枚举的原因只有一组变量)?我从来没有使用过它们,当我第一次认为它们会有用时,它们不能满足我的需求。而在网上冲浪时,我发现了很多其他的情况,比如我.. – 2012-01-18 23:48:26
@Makers_F:枚举完全按照他们的设计做。但是它们不能被扩展,所以不是多态的。你的设计需要多态性,所以不要使用枚举。 – 2012-01-18 23:56:31