CSharp · Console
using System;
public class Program
{
public static void Main()
{
var context = new Context();
context.Handle();
context.Handle();
}
}
public class Context
{
public State State{get;set;}
public Context()
{
State = new StateA(this);
}
public void Handle()
{
State.Handle();
}
}
public abstract class State
{
protected Context Context{get;set;}
public abstract void Handle();
protected abstract void ChangeState();
}
public class StateA: State
{
private bool changeState=false;
public StateA(Context context)
{
Context = context;
}
public override void Handle()
{
Console.WriteLine("This is handle method of StateA.");
changeState =true;
ChangeState();
}
protected override void ChangeState()
{
if(changeState)
Context.State = new StateB(Context);
}
}
public class StateB: State
{
private bool changeState=false;
public StateB(Context context)
{
Context = context;
}
public override void Handle()
{
Console.WriteLine("This is handle method of StateB.");
changeState=true;
ChangeState();
}
protected override void ChangeState()
{
if(changeState)
Context.State = new StateA(Context);
}
}