码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-07-13 17:40:14      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:状态改变   控制   特定   定义   request   通过   handle   书籍   oid   

 

定义:

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

 

应用场景:

角色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在特定状态下该有的行为。

 

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

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

标签:状态改变   控制   特定   定义   request   通过   handle   书籍   oid   

原文地址:http://www.cnblogs.com/fws94/p/7161663.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!