对状态模式的一点理解

看了 《游戏编程模式》这本书中的第七章的状态模式 ,对里面状态模式有了理解,也佩服作者能用形象的c++代码阐述的清晰,至少我可以理解,光看别人写的代码觉得自己都理解,可是我想用C#实现下,毕竟我现在靠C#这么语言吃饭,不多说直接开始。

开始前的一些说明:下面的代码是
1通过键盘控制一个英雄,英雄有两个状态,站立和跑路 ,
2 在站立的时候,可能有许多要做的事,比如交易,闲聊的等
3 在跑路的时候,可能要攻击 ,也可能被攻击
4 把两个状态独立成类,各自处理各自的事情,

见代码
英雄 Hero.cs

using UnityEngine;
using System.Collections;
using State;

public class Hero : MonoBehaviour {

    private StateBase m_state;
    // Use this for initialization
    void Start () {
        m_state = new StandState();
    }

    // Update is called once per frame
    void Update () {
        //这里是返回切换的状态为当前状态(根据对英雄的操作 输入确定状态)
        StateBase state = m_state.Update(Input.inputString);
        if (state != null)
        {
            m_state.Dispose();
            m_state = state;

            m_state.Enter();
        }

    }
}

状态基类 StateBase.cs

using System;
using System.Collections.Generic;
using UnityEngine;
namespace State
{
    /// <summary>
    /// 状态的基类
    /// </summary>
    abstract class StateBase
    {
        //代表这个状态所需要的资源 
        protected string m_resName;
        //每个子类都有重写的方法  这里只负责切换状态
        public abstract StateBase Update(string inputStr);
        //销毁资源的方法
        public virtual void Dispose()
        {
            Debug.Log("销毁-"+m_resName+"-本状态的资源" );
        }

        //这个状态 需要干的活
        public virtual void Enter()
        {

        }
    }
}

站立状态 StandState.cs

using System;
using System.Collections.Generic;
using UnityEngine;

namespace State
{
    class StandState:StateBase
    {
        public StandState()
        {
            m_resName = "Stand";
        }
        public override StateBase Update(string inputStr)
        {
            if (inputStr.Equals("b"))
            {
                Debug.Log("stand");
                return new RunState();
            }
            return null;
        }

        public override void Enter()
        {
            Debug.Log("Stand");
        }
    }
}

跑路状态 RunState.cs

using System;
using System.Collections.Generic;
using UnityEngine;

namespace State
{
    class RunState:StateBase
    {
        public RunState()
        {
            m_resName = "Run";
        }
        public override StateBase Update(string inputStr)
        {
            if (inputStr.Equals("a"))
            {
                //这里只负责切换状态
                return new StandState();
            }
            return null;
        }

        public override void Enter()
        {
            Debug.Log("run");
        }
    }
}

在 unity中新建一个场景,将Hero挂在摄像机上,就可以运行了 ,按a,b键 就可以看到打印的切换状态了,以上便是我对状态模式的最新理解,学习一下 就要写下来,发现写下来 又是一种加深的理解!感谢csdn!

发布了38 篇原创文章 · 获赞 14 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/sinat_23156865/article/details/59731168