我想實現一個命令模式。我有以下幾點:實現命令模式和多態性
public class State
{
public int Number { get; set; }
public void Execute(IAction action)
{
if (action.IsValid(this))
action.Apply(this);
}
}
public interface IAction
{
bool IsValid(State state);
void Apply(State state);
}
public class ActionSet5IfZero : IAction
{
public bool IsValid(State state)
{
if (state.Number == 0)
return true;
else
return false;
}
public void Apply(State state)
{
state.Number = 5;
}
}
而且程序:
static void Main(string[] args)
{
State s = new State();
s.Execute(new ActionSet5IfZero());
}
按預期工作。我的問題開始,當我想延長State類:
public class ExtendedState : State
{
public int Number2 { get; set; }
}
現在的動作必須在ExtendedState
應用更改。所以我想我會創建具有采取ExtendedState
作爲參數的兩個附加的功能擴展行動:
public class ExtendedActionSet5IfZero : IAction
{
public bool IsValid(State state)
{
throw new NotImplementedException();
}
public void Apply(State state)
{
throw new NotImplementedException();
}
public bool IsValid(ExtendedState state)
{
if (state.Number == 0 && state.Number2 == 0)
return true;
else
return false;
}
public void Apply(ExtendedState state)
{
state.Number = 5;
state.Number2 = 5;
}
}
這事我已經不喜歡,因爲實現接口的功能變得多餘。此外,我需要在我的ExtendedState
中創建一個新的Execute
函數,它使用新類型而不是IAction(否則未實現的函數會被調用)。
我相信它可以用一個很好的OO方式完成。你能幫我嗎?其目的是創建一個可擴展的State類和IAction接口(可能甚至是通用的,我不知道),所以我可以擴展State
,但仍然是通用功能,無需額外編碼。
我以前試過這個。問題是當我擴展State類並嘗試重用Execute函數時。 IAction類型與IAction 無關,我得到異常。 –
2012-02-09 17:00:30