You have to create an interface with a method for the action to do in a specific state, then you have to create concreate classes for each state and implement the method to implement the state, then you need a context to switch the states. The client will use the context to change the states.
public interface IStatus
{
void ApplyStatus();
}
public class StateInit : Status
{
void ApplyStatus()
{
InitializeMachine();
}
}
public class StateRunning : Status
{
public void ApplyStatus()
{
RunMachine();
}
}
public class StateStop : Status
{
public void ApplyStatus()
{
StopMachine();
}
}
public class Context
{
private Status state,
public void SetStatus(Status status)
{
state = status;
}
public ChangeStatus()
{
state.ApplyStatus();
}
}
{
public void ApplyStatus()
{
StopMachine();
}
}
public class Context
{
private Status state,
public void SetStatus(Status status)
{
state = status;
}
public ChangeStatus()
{
state.ApplyStatus();
}
}
Usage:
Contex contex;
context.SetStatus(new StateInit());
context.ChangeStatus();
context.SetStatus(new StateRunning());
context.ChangeStatus();
context.SetStatus(new StateStop());
context.ChangeStatus();
Nessun commento:
Posta un commento