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