其他分享
首页 > 其他分享> > 状态模式 01

状态模式 01

作者:互联网

状态之开关控制

    public class Switch
    {
        public State State = new OffState();

        public void On() { State.On(this); }
        public void Off() { State.Off(this); }
    }
    public abstract class State
    {
        public virtual void On(Switch sw) 
        {
            Console.WriteLine("Light is already on.");
        }
        public virtual void Off(Switch sw)
        {
            Console.WriteLine("Light is already off.");
        }
    }

    public class OnState:State
    {
        public OnState()
        {
            Console.WriteLine("The Light turned on.");
        }
        public override void Off(Switch sw)
        {
            Console.WriteLine("The Light turned off...");
            sw.State = new OffState(); 
        }
    }
    public class OffState:State
    {
        public OffState()
        {
            Console.WriteLine("The Light turned off.");
        }
        public override void On(Switch sw)
        {
            Console.WriteLine("The Light turned on...");
            sw.State = new OnState();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var ls = new Switch();
            ls.On();
            ls.Off();
            ls.Off();
        }
    }

 

标签:状态,01,Console,void,模式,State,WriteLine,Off,public
来源: https://www.cnblogs.com/Zingu/p/16446299.html