zoukankan      html  css  js  c++  java
  • C# 装饰模式(Decorate)

    作用:针对已经有固定功能的类,想要添加新的小功能或者属性,把这些小功能或者属性放到装饰类里,客户端可以动态地选择用哪些装饰类去修饰原有的类。代码如下:

    using System.Windows.Forms;

    namespace DesignMode.Decorate
    {
        //手机
        public class Mobile
        {
            public virtual void Play()
            {
                MessageBox.Show("Play Mobile");
            }
        }

        //装饰类
        public class MyDecorate : Mobile
        {
           protected Mobile _mobile;

           public void Decorate(Mobile mobile)
           {
               this._mobile = mobile;
           }

           public override void Play()
           {
               if (_mobile != null)
               {
                   _mobile.Play();
               }
           }
        }

        public class OpenGPS : MyDecorate
        {
            public override void Play()
            {
                MessageBox.Show("开通GPS");
                base.Play();
            }
        }

        public class Shell : MyDecorate
        {
            public override void Play()
            {
                MessageBox.Show("装上外壳");
                base.Play();
            }
        }

        public class Alarm : MyDecorate
        {
            public override void Play()
            {
                MessageBox.Show("设定闹钟");
                base.Play();
            }
        }

    }  

    客户端代码:

            private void btn_Decorate_Click(object sender, EventArgs e)
            {
                Mobile mobile = new Mobile();

                //设闹钟,开通GPS
                OpenGPS gps = new OpenGPS();
                Alarm alarm = new Alarm();
                gps.Decorate(mobile);
                alarm.Decorate(gps);
                alarm.Play();

            } 

  • 相关阅读:
    JS事件
    BOM
    DOM
    常见的SQL字符串函数
    常用的认证方式
    后台代码扫描规则-sonarQube官方
    spring cloud中feign的使用
    常见基于 REST API 认证方式
    Java中连接池
    这是一张心情贴
  • 原文地址:https://www.cnblogs.com/kavilee/p/2360765.html
Copyright © 2011-2022 走看看