您的位置:首页 > 编程语言 > C#

201802272223->深入浅出设计模式:c#状态模式

2018-02-27 22:24 489 查看
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace _020状态模式

{

    public interface LightState

    {

        void Press(Light light);

    }

    public class TurnOff : LightState

    {

        public void Press(Light light)

        {

            light.State = new TurnOn();

            Console.WriteLine("turn on the light");

        }

    }

    public class TurnOn : LightState

    {

        public void Press(Light light)

        {

            light.State = new TurnOff();

            Console.WriteLine("turn off the light");

        }

    }

    public class Light

    {

        public LightState State;

        public Light()

        {

            this.State = new TurnOff();

        }

        public void Press()

        {

            State.Press(this);

        }

    }

    internal class Program

    {

        private static void Main(string[] args)

        {

            Light light = new Light();

            light.Press();

            light.Press();

            light.Press();

            /*

             * 状态模式

             *

             * 利用接口实现不同的逻辑,根据逻辑实现需求

             *

             * 与策略模式相似

             *

             * 但策略模式偏向外部实现逻辑,状态模式比较偏向内部实现逻辑,

             *

             * 外部只需要调用接口则可以改变对象内部的状态,实现不同的逻辑

             *

             */

            Console.ReadKey();

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 心得 理解 笔记