1.状态模式允许一个对象在其内部状态改变时改变它的行为,使对象看起来似乎修改了它的类。
2.在软件开发过程中,应用程序可能会根据不同的情况作出不同的处理。最直接的解决方案是将这些所有可能发生的情况全都考虑到,然后使用(if else(或switch case)语句来做状态判断来进行不同情况的处理。
但是编程中如果一个方法中有很多判断就是坏味道了。假如我有10个、100个状态,如果还是用(if else(或switch case)来做判断那岂不是会累死?
再假如我需要增加或修改一个状态,可能得需要大刀阔斧地进行修改,而程序的可读性、扩展性也会变得很弱,稍一部小心可能就会出错,维护起来也会很麻烦。这下我们就可以考虑使用状态模式解决此问题,只修改自身的状态即可。
3.状态模式结构
Conetext:是总管理器,维护一个ConcreteState子类的实例,它可以定义当前的状态。
State:定义了一个所有具体状态的共同接口,也可以是抽象类,任何状态都实现这个相同的接口,这样一来,状态之间可以相互替换。
ConcreteState:是实现具体功能的类,处理来自Context的请求。每一个ConcreteState都提供了它自己对于请求的实现,所以,当Context状态发生改变时行为它也跟着改变。具体的状态可以有很多个。
并且可以在ConcreteState里切换Conetext的状态,需要获取管理器。
简单例子:
实现功能:Led灯切换颜色
状态切换方法:迭代器方式
Led状态接口:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface ILedState {//接口类(类似于一种约定规则)
void lightLed(LedStateController ledStateController);//切换颜色的接口方法
//获得控制器用于切换状态
}
Led状态管理器:
若无设置则默认红灯
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LedStateController {
public ILedState ledState;//接口类声明
public LedStateController(){
ledState = new RedState();
Debug.Log("默认红灯");
}
public LedStateController(ILedState ledState){
this.ledState = ledState;
Debug.Log("默认设置:");
}
public void SwitchLed(){//切换LED颜色
ledState.lightLed(this);//传入当前控制器
}
}
颜色的功能实现类:
状态切换方法:迭代器方式
绿》蓝》红》绿....
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GreenState : ILedState {//继承接口
public void lightLed(LedStateController ledStateController){
Debug.Log("绿灯");
ledStateController.ledState = new BlueState();//改变控制器状态
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlueState : ILedState {//继承接口
public void lightLed(LedStateController ledStateController){
Debug.Log("蓝灯");
ledStateController.ledState = new RedState();//改变控制器状态
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RedState : ILedState {//继承接口
public void lightLed(LedStateController ledStateController){
Debug.Log("红灯");
ledStateController.ledState = new GreenState();//改变控制器状态
}
}
Main方法:使用状态模式
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test01Main : MonoBehaviour {
public LedStateController ledStateController;
// Use this for initialization
void Start () {
ledStateController = new LedStateController(new RedState());
ledStateController.SwitchLed();
ledStateController.SwitchLed();
ledStateController.SwitchLed();
ledStateController.SwitchLed();
ledStateController.SwitchLed();
}
// Update is called once per frame
void Update () {
}
}
结果: