I´m trying to implement the State-Pattern using C# following this page. Here the UML of a State-Pattern.
The State it self sets the new sate in the context class. But here is my problem: I want to use Interfaces but the ChangeState-Method should not be present to the client but available for the state. But I don´t know how to implement a private interface within a class which I present for the client.
Here my first shot of the pattern Context-Class which should implement the IChangeState interface:
public interface IContext
{
string Input { get; set; }
void DoTransition();
}
public class Context : IContext
{
public string Input { get; set; }
private AbstractState _state;
public void DoTransition()
{
_state.DoTransition();
}
}
And the IChangeState interface which does the main trick but should not be visibile to the client. So I assumed to make it private but how to share this interface with the state or even implement it?
public interface IChangeState
{
void ChangeState(IState state);
}
And at least the States:
public interface IState
{
void DoTransition();
}
public abstract class AbstractState : IState
{
private IChangeState _stateChanger;
public AbstractState(IChangeState stateChanger) => _stateChanger = stateChanger;
public virtual void DoTransition()
{
_stateChanger.ChangeState(new NextState(_stateChanger));
}
}
public class NextState : AbstractState
{
public NextState(IChangeState stateChanger)
: base(stateChanger)
{ }
public override void DoTransition()
{
base.DoTransition();
}
}
Aucun commentaire:
Enregistrer un commentaire