【Unity3D与23种设计模式】状态模式(State)

 

定义:

“让一个对象的行为随着内部状态的改变而变化,而该对象也像是换了类一样”

 

应用场景:

角色AI:控制角色在不同状态下的AI行为

服务器连接状态:开始连线、连线中、断线等状态

关卡进行状态:不同关卡

 

using System;
 using UnityEngine;

public class Context {
     State m_State = null;

    public void Request(int Value) {
         m_State.Handle(Value);
     }

    public void SetState(State theState) {
         Debug.Log("Context.SetState:" + theState);
         m_State = theState;
     }
 }

public abstract class State {
     protected Context m_Context = null;
     public State(Context theConText) {
         m_Context = theConText;
     }
     public abstract void Handle(int Value);
 }

//状态A
 public class ConcreteStateA : State {
     public ConcreteStateA(Context theContext) : base(theContext) { }

    public override void Handle(int Value)
     {
         Debug.Log("ConcreteStateA.Handle");
         if (Value > 10)
             m_Context.SetState(new ConcreteStateB(m_Context));
     }
 }

//状态B
 public class ConcreteStateB : State {
     public ConcreteStateB(Context theContext) : base(theContext) { }

    public override void Handle(int Value)
     {
         Debug.Log("ConcreteStateA.Handle");
         if (Value > 20)
             m_Context.SetState(new ConcreteStateC(m_Context));
     }
 }

//状态C
 public class ConcreteStateC : State
 {
     public ConcreteStateC(Context theContext) : base(theContext) { }

    public override void Handle(int Value)
     {
         Debug.Log("ConcreteStateA.Handle");
         if (Value > 30)
             m_Context.SetState(new ConcreteStateA(m_Context));
     }
 }

 

Context(状态拥有者)

一个具有状态属性的类,可以制定相关的接口,让外界能够得知状态的改变或通过操作让状态改变

State(状态接口类)

制定状态的接口,负责规范Context在特定状态下要表现的行为。

ConcreteState(具体状态类)

继承自State,实现Context在特定状态下该有的行为。

 

文章整理自书籍《设计模式与游戏完美开发》 菜升达 著

posted on 2017-07-13 17:29  Lumious  阅读(612)  评论(0编辑  收藏  举报

导航