关于C# 设计模式 State 状态模式

关于C# 设计模式 State 状态模式

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

///State(状态)模式用于把一个对象的内部状态从对象中分离出来,形成单独的状态对象,所有与该状态相关的行为都放入该状态对象中。
///add by jzh 2007-04-15
namespace DesignPattern
{
    abstract class State
    {
        protected string strStatename;

        abstract public void Pour();
    }

    class OpenedState : State
    {
        public OpenedState()
        {
            strStatename = "打开";
        }
        override public void Pour()
        {
            Console.WriteLine("...pouring...");
            Console.WriteLine("...pouring...");
            Console.WriteLine("...pouring...");
        }
    }

    class ClosedState : State
    {
        public ClosedState()
        {
            strStatename = "关闭";
        }
        override public void Pour()
        {
            Console.WriteLine("关闭");
        }
    }

    class ContextColaBottle
    {
        public enum BottleStateSetting
        {
            Closed,
            Opened
        };

        OpenedState openedState = new OpenedState();
        ClosedState closedState = new ClosedState();

        public ContextColaBottle()
        {
            CurrentState = closedState;
        }

        private State CurrentState;

        public void SetState(BottleStateSetting newState)
        {
            if (newState == BottleStateSetting.Closed)
            {
                CurrentState = closedState;
            }
            else
            {
                CurrentState = openedState;
            }
        }

        public void Pour()
        {
            CurrentState.Pour();
        }
    }

    public class Client
    {
        public static void Main(string[] args)
        {
            ContextColaBottle contextColaBottle = new ContextColaBottle();

            Console.WriteLine("释放");
            contextColaBottle.Pour();

            Console.WriteLine("打开");
            contextColaBottle.SetState(ContextColaBottle.BottleStateSetting.Opened);

            Console.WriteLine("释放");
            contextColaBottle.Pour();

            Console.ReadLine();
        }
    }
}

 

发表回复

您的电子邮箱地址不会被公开。