1. 程式人生 > >C#設計模式-狀態模式

C#設計模式-狀態模式

using System;
using System.Collections.Generic;

namespace TestCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            PlayerFSM fsm = new PlayerFSM();
            fsm.SetState(new Walk());
            fsm.Update();
            fsm.SetState(new Attack());
            fsm.Update();

            Console.ReadKey();
        }

        abstract class State
        {
            public abstract void Handle();
        }

        class Walk : State
        {
            public override void Handle()
            {
                Console.WriteLine("Walk");
            }
        }
        
        class Attack : State
        {
            public override void Handle()
            {
                Console.WriteLine("Attack");
            }
        }

        class PlayerFSM
        {
            State m_CurState;

            public void Update()
            {
                m_CurState.Handle(); 
            }

            public void SetState(State state)
            {
                m_CurState = state; 
            }
        }
    }
}