zoukankan      html  css  js  c++  java
  • 设计模式之装饰者模式2

    在oo中,一般有2中方式可以实现给一个类或对象增加行为:

    1.继承机制

     使用继承机制给现有类增加 功能,这种方法是静态的,用户 不能控制增加行为的方式和时机

    2.关联机制

     关联机制是一种更加灵活的方法,即将一个类的对象嵌入到另一个对象中,由另一个对象来决定是否调用嵌入对象的行为并扩展自己的行为,我们称这个对象为装饰器(decorator)。为了使得装饰器与他所装饰的对象对客户端来说透明,装饰器类和被装饰的类必须实现相同的接口,客户端使用时无需关心一个类的对象是否被装饰过,可以一致性第使用未被装饰的对象以及装饰好的对象

      

    装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任,换言之,客户端并不会觉得对象在装饰前后有什么不同。

    定义:

    Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

     The classes and/or objects participating in this pattern are:

    • Component   (LibraryItem)
      • defines the interface for objects that can have responsibilities added to them dynamically.
    • ConcreteComponent   (Book, Video)
      • defines an object to which additional responsibilities can be attached.
    • Decorator   (Decorator)
      • maintains a reference to a Component object and defines an interface that conforms to Component's interface.
    • ConcreteDecorator   (Borrowable)
      • adds responsibilities to the component.
     
    我们在Decorator或concreteDecorator中,可以写一个相同的方法调用被装饰对象的方法,也可以引入其他的方法。
    例子:http://www.dofactory.com/Patterns/PatternDecorator.aspx#_self1
     
  • 相关阅读:
    mybatis与spring的整合(代码实现)
    使用maven构建一个web项目
    解决maven 找不到指定路径应该如何
    建一个maven项目
    spring xml的配置
    mybatis.xml和mapper.xml的配置
    mvc @helper 创建用户自定义html
    sqlserver CLR sqlserver使用C# dll
    索引碎片
    压缩数据库
  • 原文地址:https://www.cnblogs.com/youxin/p/3071287.html
Copyright © 2011-2022 走看看