文章目录
1.UML类图 2.状态基类 3.状态实现类 3.状态机管理类 使用示例
1.UML类图
2.状态基类
public abstract class State
{
public string ? Name { get ; set ; }
public StateMachine? StateMachine { get ; set ; }
public abstract void Exit ( ) ;
public abstract void Enter ( ) ;
}
3.状态实现类
StateA
public class StateA : State
{
public StateA ( string name)
{
Name = name;
}
public override void Enter ( )
{
Console. WriteLine ( "进入状态A,Name:{0}" , Name) ;
}
public override void Exit ( )
{
Console. WriteLine ( "退出状态A,Name:{0}" , Name) ;
}
}
StateB
public class StateB : State
{
public StateB ( string name)
{
Name = name;
}
public override void Enter ( )
{
Console. WriteLine ( "进入状态B,Name:{0}" , Name) ;
}
public override void Exit ( )
{
Console. WriteLine ( "退出状态B,Name:{0}" , Name) ;
}
}
StateC
public class StateC : State
{
public StateC ( string name)
{
Name = name;
}
public override void Enter ( )
{
Console. WriteLine ( "进入状态C,Name:{0}" , Name) ;
}
public override void Exit ( )
{
Console. WriteLine ( "退出状态C,Name:{0}" , Name) ;
}
}
3.状态机管理类
public class StateMachine
{
public string ? Name { get ; set ; }
private List< State> states = new List< State> ( ) ;
private State? CurrentState;
public StateMachine ( string name)
{
Name = name;
}
public void AddState ( State state)
{
if ( ! states. Contains ( state) )
{
states. Add ( state) ;
state. StateMachine = this ;
}
}
public void RemoveState ( State state)
{
if ( states. IndexOf ( state) == - 1 )
return ;
state. Exit ( ) ;
CurrentState = null ;
states. Remove ( state) ;
}
public void ChangeState ( State state)
{
CurrentState?. Exit ( ) ;
CurrentState = state;
CurrentState. Enter ( ) ;
}
public void Switch2NextState ( )
{
if ( CurrentState != null )
{
int index = states. IndexOf ( CurrentState) ;
if ( index == - 1 )
return ;
if ( index + 1 >= states. Count)
return ;
CurrentState. Exit ( ) ;
CurrentState = states[ index + 1 ] ;
}
else
{
CurrentState = states[ 0 ] ;
}
CurrentState. Enter ( ) ;
}
public void Switch2PreviousState ( )
{
if ( CurrentState != null )
{
int index = states. IndexOf ( CurrentState) ;
if ( index == - 1 )
return ;
if ( index == 0 )
return ;
CurrentState. Exit ( ) ;
CurrentState = states[ index - 1 ] ;
}
else
{
CurrentState = states[ states. Count - 1 ] ;
}
CurrentState. Enter ( ) ;
}
}
使用示例
StateMachine stateMachine = new StateMachine ( "状态模式测试" ) ;
stateMachine. AddState ( new StateA ( "状态A" ) ) ;
StateB stateB = new StateB ( "状态B" ) ;
stateMachine. AddState ( stateB) ;
stateMachine. AddState ( new StateC ( "状态C" ) ) ;
stateMachine. Switch2NextState ( ) ;
stateMachine. Switch2NextState ( ) ;
stateMachine. Switch2NextState ( ) ;
stateMachine. Switch2PreviousState ( ) ;
stateMachine. Switch2PreviousState ( ) ;
stateMachine. ChangeState ( stateB) ;