装饰模式(Decorator Pattern)
The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class.
This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).
1、Component
-定义一个对象接口,可以给这些对象动态地添加职责。
2、ConcreteComponent
-定义一个对象,可以给这个对象添加一些职责。
3、Decorator
-维持一个指向Component对象的指针,并定义一个于Component接口一致的接口。
4、ConcreteDecorator
-向组件添加职责。
interface Component { public void operation(); }
class ConcreteComponent implements Component { public void operation() { } }
class Decorator implements Component { private Component component; public Decorator(Component component) { this.component=component; } public void operation() { component.operation(); } }
class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component component) { super(component); } public void operation() { super.operation(); decoratorFunction(); } public void decoratorFunction() { } }
装饰模式在java中的最著名的应用: Java I/O 标准库。
《设计模式:可复用面向对象软件的基础》
原文:https://www.cnblogs.com/diameter/p/13192277.html