I want to implement a command pattern. I have the following:
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;
}
}
And the program:
static void Main(string[] args)
{
State s = new State();
s.Execute(new ActionSet5IfZero());
}
That works as expected. My problem begins, when I would like to extend the State class:
public class ExtendedState : State
{
public int Number2 { get; set; }
}
Now the action must apply changes on ExtendedState. So I thought I would create extended action that has two additional functions that take ExtendedState as a parameter:
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;
}
}
This is something I already do not like because the functions that implement the interface become redundant. Moreover I need to create a new Execute function in my ExtendedState that utilizes the new type and not IAction (otherwise not implemented functions get called).
I am sure it can be done in a nice OO way. Can you help me out? The aim is to create an extensible State class and IAction interface (maybe even generic, I do not know), so I can extend the State but remain the generic functionality without additional coding.