zoukankan      html  css  js  c++  java
  • 《大话设计模式》学习笔记3:装饰模式

      

      

    穿衣服示例:

      

    1.ConcreteComponent(人类):

        public class Person
        {
            public virtual void Show()
            {
                Console.Write("开始装扮:");
            }
        }

    2.Decorator(服饰类):

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

    3.ConcreteDecorator(具体服饰类,以垮裤类为例):

        public class BigTrouser:Finery
        {
            public override void Show()
            {
                base.Show();//首先运行原Component的操作,再执行本类的操作
                Console.Write("垮裤 ");
            }
        }

    4.客户端代码:

        class Program
        {
            static void Main(string[] args)
            {
                Person person = new Person();
                BigTrouser bigTrouser = new BigTrouser();
                TShirts tShirts = new TShirts(); 
                LeatherShoes leatherShoes = new LeatherShoes();
    
                bigTrouser.Decorate(person);
                tShirts.Decorate(bigTrouser);
                leatherShoes.Decorate(tShirts);
    
                leatherShoes.Show();
            }
        }

      如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

      装饰模式是为已有功能动态添加更多功能的一种方式。

      优点:有效地把类的核心职责和装饰功能区分开,而且可以去除相关类中重复的逻辑。

  • 相关阅读:
    慎重使用MySQL auto_increment
    Java Tread多线程(0)一个简单的多线程实例
    Nubia Z5S 官方4.4 201内測版 内核版本号信息
    “cvSnakeImage”: 找不到标识符
    raid5什么意思?怎样做raid5?raid5 几块硬盘?
    Quartz CronTrigger运用
    php zip文件内容比較类
    UVA 1069
    Eclipse启动Tomcat时,45秒超时解决方案
    簡單SQL存儲過程實例
  • 原文地址:https://www.cnblogs.com/walden1024/p/4487741.html
Copyright © 2011-2022 走看看