状态模式

作者:追风剑情 发布于:2016-6-5 15:31 分类:设计模式

应用场景:当有多个状态时,不同的状态对应不同的行为

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StateTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Context context = new Context();
            context.SetState(new StateA());//设置初始状态
            Console.WriteLine(context.GetState().ToString());

            context.Next();
            Console.WriteLine(context.GetState().ToString());

            context.Next();
            Console.WriteLine(context.GetState().ToString());

            Console.Read();
        }
    }

    interface IState
    {
        string ToString();
        void Next(Context c);
    }

    class StateA : IState
    {
        public string ToString()
        {
            return "State A";
        }
        public void Next(Context c)
        {
            c.SetState(new StateB());
        }
    }

    class StateB : IState
    {
        public string ToString()
        {
            return "State B";
        }
        public void Next(Context c)
        {
            c.SetState(new StateC());
        }
    }

    class StateC : IState
    {
        public string ToString()
        {
            return "State C";
        }
        public void Next(Context c)
        {
            c.SetState(new StateA());
        }
    }

    class Context
    {
        private IState state;

        public IState GetState()
        {
            return state;
        }

        public void SetState(IState state)
        {
            this.state = state;
        }

        public void Next()
        {
            state.Next(this);
        }
    }
}

运行效果

2222.jpg

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号