Design Principle
Classes should be open for extension, but closed for modification.
Goal is to allow classes to be easily extended to incorporate new behavior without modifying existing code.
Meet the Decorator Pattern
- Decorators have the same supertype as the objects they decorate.
- You can use one or more decorators to wrap an object.
- Given that the decorator has the same supertype as the object it decorates, we can pass around a decorated object in place of the original (wrapped) object.
- The decorator adds its own behavior either before and/or after delegating to the object it decorates to do the rest of the job.
- Objects can be decorated at any time, so we can decorate objects dynamically at runtime with as many decorators as we like.
The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Real World Decorators: Java I/O
BufferedInputStream and
LineNumberInputStream both extend
FilterInputStream, which acts as the abstract decorator class.
OO Principles
Classes should be open for extension but closed for modification.
OO Patterns
Decorator- Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.