110 likes | 124 Views
Learn about the Decorator pattern, a flexible alternative to subclassing for attaching additional responsibilities dynamically. Explore its structure, applicability, consequences, and relationship with the Open-Closed Principle. Enhance object functionalities easily and efficiently.
E N D
Decorator Pattern Richard Gesick
Pattern Overview • The Decorator pattern provides a flexible alternative to subclassing by attaching additional responsibilities to an object dynamically, by using an instance of a subclass of the original class that delegates operations to the original object • This pattern type falls into the Structural Patterns category and deals with objects.
Structure -- UML Construction • The ConcreteComponent is the object that can be decorated • An instance variable is included in the ConcreteDecorator for the object that it will decorate.
As seen in the diagram each component can be used on its own or wrapped by a decorator. • Decorators extend the state of the component. • Additionally they implement the same interface or abstract class as the component they are going to decorate
Attach additional responsibilities to an object dynamically. • Decorators provide a flexible alternative to subclassing for extended functionality.
Applicability • Need to add responsibilities to objects dynamically and transparently • Need to withdraw responsibilities • Need to support large combinations of responsibilities without a class explosion • When extension by subclassing is impractical or impossible
Consequences • More flexible than static inheritance • Avoids feature-laden classes high up in the hierarchy • A decorator and its component aren't identical • Decorators can be an effective, less-confusing and more easily maintainable substitute for multiple-inheritance.
Lots of little objects! • Functionality of a class can be extended knowing only its interface; source is not always required. Therefore, the class is closed to modification, but open to extension. • Decorators allow more flexibility to code by avoiding extending your class hierarchy just to support a characteristic. • Resources are used as they are needed since run-time objects are created.
The Open-Closed Principle • Design Principle: Classes should be open for extension, but closed for modification. • Our goal is to allow classes to be easily extended to incorporate new behavior without modifying existing code.
This gives us designs that are resilient to change and flexible enough to take on new functionality to meet changing requirements. • Be careful when choosing the areas of code that need to be extended; applying the Open-Closed Principle EVERYWHERE is wasteful, unnecessary, and can lead to complex, hard to understand code.