有需要的同学也可以这样写; 我不太喜欢让子持有父, 所以让子返回信息给父
//控制
public class Context
{
//由于state是私有的,外部不能访问,所以需要提供以下方法
private IState state;
//封装一次方法
public void Handle(int num)
{
IState tempState = this.state.Handle(num);
if (tempState != null)
this.ChangeState(tempState);
}
//切换状态
public void ChangeState(IState state)
{
this.state = state;
}
}
//接口
public interface IState
{
public IState Handle(int num);
}
//实现接口
public class StateA : IState
{
public IState Handle(int num)
{
Debug.Log(this + " " + num);
if (num > 10)
return new StateB();
else
return null;
}
}
//实现接口
public class StateB : IState
{
public IState Handle(int num)
{
Debug.Log(this + " " + num);
if (num <= 10)
return new StateA();
else
return null;
}
}