三明治

装饰器(Decorator)模式

痞子三分冷 提交于 2019-11-27 14:19:33
转自: http://miaoxiaodong78.blog.163.com/blog/static/18765136200701232434996/ Decorator 设计模式是典型的结构型模式(在 GOF 的那本模式的 Bible 中将模式分为: 1. 创建型模式; 2. 结构型模式; 3. 行为模式三种)。它的主要用意是: 动态地 为对象 添加 一些额外的 功能 。(记住上面两种颜色的词汇,理解装饰器模式的精髓所在!)下面是 GOF 的《 Element of reusable Object-Oriented Software 》中对 Decorator 用意的概述: Decorator Pattern ―― Attaches additional responsibilities to an object dynamically . Decorators provide a flexible alternative to subclassing for extending functionality . 1 何时需要使用装饰器模式 GOF 的那本 Bible 中关于装饰器模式列举的是一个文本组件与边框的例子(在这里我就不举了,主要是因为我会在书中举一个相似的,但却非常有说服力的例子,它对 Swing 中的某些本来应该使用 Decorator 却没有使用的对象的改进