zoukankan      html  css  js  c++  java
  • 装饰模式 -- 大话设计模式

    在今天,读书有时是件“麻烦”事。它需要你付出时间,付出精力,还要付出一份心境。--仅以《大话设计模式》来祭奠那逝去的……

    装饰模式:动态的给一个对象增加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活(适合场景,需要经常动态的添加额外职责的时候使用。稳定的业务不建议使用装饰模式,增加不必要的代码量)

    1.装扮小游戏

      给要出门的小伙子打扮一下,衣服都在衣橱里面,挑选一下打扮起来

      首先建立一个人物模型Person

        public class Person
        {
            public Person() { }
    
            private string _name;
    
            public Person(string name)
            {
                this._name = name;
            }
    
            public virtual void Show()
            {
                Console.WriteLine("装扮的{0}", _name);
            }
        }
    

       其次定义一个装饰类,装饰类要继承人物模型类,将人物模型内置到装饰类中,方便装饰处理

        public class Finery : Person
        {
            protected Person _component;
    
            public void Decorate(Person person)
            {
                this._component = person;
            }
    
            public override void Show()
            {
                if (_component != null)
                    _component.Show();
            }
        }
    

       定义各种服饰类,继承装饰类,实现装饰人物模型的功能

        public class TShirts : Finery
        {
            public override void Show()
            {
                Console.Write("大T恤 ");
                base.Show();
            }
        }
    
        public class BigTrouser : Finery
        {
            public override void Show()
            {
                Console.Write("垮裤 ");
                base.Show();
            }
        }
    

       开始装饰人物模型,实例化一个模型“小张”,首先给小张穿上垮裤,然后是T恤,就可以出门了(装饰模式是一个链式调取方式,由外到内或者是由下到上

            static void Main(string[] args)
            {
                //装饰模式
                Person person = new Person("小张");
    
                //再穿一个大T恤
                TShirts dtx = new TShirts();
                dtx.Decorate(person);
    
                //先穿一个垮裤
                BigTrouser kk = new BigTrouser();
                kk.Decorate(dtx);
    
                //可以出门了
                kk.Show();
            }
    

       来看看帅帅的小张吧

      

  • 相关阅读:
    回调函数实例
    Java StringBuffer 和 StringBuilder 类
    excel被保护或者锁定时候按住alt和enter可以输入换行
    ArrayUtils.
    excel中在某一列上的所有单元格的前后增加
    decode(条件,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值)
    正则表达式:Pattern类与Matcher类详解
    Cocos2d-x文本菜单
    msp430在ccsv5下出现的问题总结
    与TCP/IP协议的初次见面(一)
  • 原文地址:https://www.cnblogs.com/amywechat/p/4919546.html
Copyright © 2011-2022 走看看