我想实现一个命令模式。我有以下内容:
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;
}
}
这是我已经不喜欢的东西,因为实现接口的函数变得多余。此外,我需要Execute
在我的中创建一个ExtendedState
使用新类型而不是 IAction 的新函数(否则将调用未实现的函数)。
我相信它可以以一种很好的 OO 方式完成。你能帮我吗?目的是创建一个可扩展的 State 类和 IAction 接口(甚至可能是通用的,我不知道),所以我可以扩展State
但保持通用功能而无需额外编码。