zoukankan      html  css  js  c++  java
  • C# 设计模式(21)状态模式

    状态模式

    代码实现:

    交通类:

    namespace StatePattern
    {
        public abstract class BaseLight
        {
            private LightColor _lightColor;
    
            public abstract void Show();
            public abstract void TurnContext(Context context);
        }
        public enum LightColor
        {
            Green,
            Yellow,
            Red
        }
        public class LightGreen:BaseLight
        {
            public override void Show()
            {
                Console.WriteLine("CurrentLight color is green,you can go.");
            }
    
            public override void TurnContext(Context context)
            {
                context.CurrentLight = new LightYellow();
            }
        }
        public class LightYellow : BaseLight
        {
            public override void Show()
            {
                Console.WriteLine("CurrentLight color is Yellow,you can be careful.");
            }
    
            public override void TurnContext(Context context)
            {
                context.CurrentLight = new LightRed();
            }
        }
        public class LightRed:BaseLight
        {
            public override void Show()
            {
                Console.WriteLine("CurrentLight color is Red,you must stop.");
            }
    
            public override void TurnContext(Context context)
            {
                context.CurrentLight = new LightGreen();
            }
        }
    }

    上下文:

        public class Context
        {
            public BaseLight CurrentLight { get; set; }
    
            public void Show()
            {
                this.CurrentLight.Show();
            }
    
            public void Turn()
            {
                this.CurrentLight.TurnContext(this);
            }
        }
    

    代码调用:

        class Program
        {
            static void Main(string[] args)
            {
                Context context = new Context();
                context.CurrentLight = new LightGreen();
                context.Show();
                context.Turn();            
                context.Show();
                context.Turn();           
                context.Show();
                context.Turn();
                context.Show();
                context.Turn();
            }
        }

    结果:

  • 相关阅读:
    五、drf路由组件
    四、drf视图组件
    三、drf请求&响应
    二、drf序列化器
    解决SQL Server管理器无法连接远程数据库的问题
    常见网络摄像机(摄像头)的端口及RTSP地址
    海康、大华网络摄像机RTSP URL格式组成及参数配置
    SQL 查询某字段不为空
    SqlServer中保留几位小数的两种做法
    sql重复数据只取一条记录
  • 原文地址:https://www.cnblogs.com/YourDirection/p/14102561.html
Copyright © 2011-2022 走看看