zoukankan      html  css  js  c++  java
  • 设计模式学习笔记(2)之装饰模式(Decorator)

    作用:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生产子类更为灵活。

    结构图

    客户端调用:利用SetComponent来对对象进行包装。把每个装饰对象的实现和使用这个对象分立开,每个装饰对象只关心自己的功能,不需要关心对象如何被添加到对象连当中(DPE)。

    适用性

    在以下情况下应当使用装饰模式:

    1.需要扩展一个类的功能,或给一个类增加附加责任。

    2.需要动态地给一个对象增加功能,这些功能可以再动态地撤销。

    3.需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。

    模式总结:

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

    2、当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,在主类中加入新的字段,新的方法和新的逻辑,从而增加了主类的复杂度。这些加入的东西是为了满足一些只有在特定情况下才回执行的特殊行为需求。

    3、装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装他需要的装饰对象,当需要执行特殊行为时,客户端就可以运行时根据需要有选择地、按顺序地使用装饰功能包装对象[DP]。

    4、把类中的装饰功能从类中搬移出去,简化原有类,有效地把类的核心职责和装饰功能区分开,可以去除相关类中重复的装饰逻辑。

    附件代码:

    View Code
     class ConcreteComponent : Component
        {
    
            public override void Operation()
            {
    
                Console.WriteLine("this is based");
    
            }
    
        }
        abstract class Decorator : Component
        {
    
            protected Component component;
            public void SetComponent(Component component)
            {
    
                this.component = component;
    
            }
            public override void Operation()
            {
    
                if (component != null)
                {
    
                    component.Operation();
    
                }
    
            }
    
        }
        class ConcreteDecoratorA : Decorator
        {
            private string addedState;
            public override void Operation()
            {
    
                base.Operation();
    
                addedState = "New State";
    
                Console.WriteLine(addedState + " this is A Decorator");
    
            }
    
        }
    
        class ConcreteDecoratorB : Decorator
        {
            public override void Operation()
            {
    
                base.Operation();
    
                AddedBehavior();
    
                Console.WriteLine("this is B Decorator");
    
            }
    
            private void AddedBehavior()
            {
    
                Console.WriteLine("B AddedBehavior");
    
            }
    
        } 
     


    作者:追梦网络
    出处:http://www.cnblogs.com/dream844/
    本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    使用 libevent 和 libev 提高网络应用性能
    An existing connection was forcibly closed by the remote host
    各种浏览器的兼容css
    vs输出窗口,显示build的时间
    sass
    网站设置404错误页
    List of content management systems
    css footer not displaying at the bottom of the page
    强制刷新css
    sp_executesql invalid object name
  • 原文地址:https://www.cnblogs.com/dream844/p/3036112.html
Copyright © 2011-2022 走看看