Code in C#:
namespace
State_DesignPattern
{
using System;
abstract class State
{
protected string strStatename;
abstract public void Pour();
// do something state-specific here
}
class OpenedState : State
{
public OpenedState ()
{
strStatename = "Opened";
}
override public void Pour()
{
Console.WriteLine("...pouring...");
Console.WriteLine("...pouring...");
Console.WriteLine("...pouring...");
}
}
class ClosedState : State
{
public ClosedState()
{
strStatename = "Closed";
}
override public void Pour()
{
Console.WriteLine("ERROR - bottle is closed - cannot pour");
}
}
class ContextColaBottle
{
public enum BottleStateSetting
{
Closed,
Opened
};
// If teh state classes had large amounts of instance data,
// we could dynamically create them as needed - if this demo
// they are tiny, so we just create them as data members
OpenedState openedState = new OpenedState();
ClosedState closedState = new ClosedState();
public ContextColaBottle ()
{
// Initialize to closed
CurrentState = closedState;
}
private State CurrentState;
public void SetState(BottleStateSetting newState)
{
if (newState == BottleStateSetting.Closed)
{
CurrentState = closedState;
}
else
{
CurrentState = openedState;
}
}
public void Pour()
{
CurrentState.Pour();
}
}
///<summary>
/// Summary description for Client.
///</summary>
public class Client
{
public static int Main(string[] args)
{
ContextColaBottle contextColaBottle = new ContextColaBottle();
Console.WriteLine("initial state is closed");
Console.WriteLine("Now trying to pour");
contextColaBottle.Pour();
Console.WriteLine("Open bottle");
contextColaBottle.SetState(ContextColaBottle.BottleStateSetting.Opened);
Console.WriteLine("Try to pour again");
contextColaBottle.Pour();
return 0;
}
}
}
Code in SOME:
AState
string m_strStatename
a_Pour()
COpenedState : AState
(string m_strStatename) /* member m_strStatename should not be defined again becuase it has already been defined by its father*/
o_Pour()
CClosedState : AState
()
o_Pour()
CContextColaBottle ->AState[_CurrentState] ->CCOpenedState[c_openedState.()] ->CClosedState[c_closedState.()]
()
SetState(string)
Pour()
CClient
main
CClient.main
{
CContextColaBottle contextColaBottle.()
{
_CurrentState = _closedState;
};
<% Console.WriteLine("initial state is closed"); %>
<% Console.WriteLine("Now trying to pour"); %>
contextColaBottle.Pour()
{
_CurrentState.Pour(); //override function should not be unfolded in this situation
};
<% Console.WriteLine("Open bottle"); %>
contextColaBottle.SetState(newState["CContextColaBottle.BottleStateSetting.Opened"]) //alias for parameter, all the content between [] will be reserved
{
<%
if (newState == BottleStateSetting.Closed)
{
_CurrentState = _closedState;
}
else
{
_CurrentState = _openedState;
}
%>
};
<% Console.WriteLine("Try to pour again");%>
contextColaBottle.Pour();
}