Please enable JavaScript.
Coggle requires JavaScript to display documents.
DECORATOR PATTERN - Coggle Diagram
DECORATOR PATTERN
UML
-
-
WORKFLOW
- Create instance of "Espresso"
- Pass instance to a caramel decorator
- Pass instance of caramel, decorated espresso to a soy decorator
Problems:
- It's hard to remember what we have
- If we are interested in order this design pattern is not suitable
GENERALIZED UML
-
- Create an instance of concrete component
- Give a Decorator and pass the component
-
-
USE CASES
BEHAVIORS
- Decorator pattern is more suitable when we need to have different behaviors/decorators
- No property variation
DEPRECTION
- I have a class used in a bunch of places
- I want to stop using the class and for some reasons I can't change it at the same time in all the places
- I create a wrapper, intercepts the call and change it
- I can use non decorated and decorated version in some places
Basic
- Decorator pattern is a way to change behavior of an class without changing it's content
- We wrap the object with an outer object who will alter the behavior of inner object
- The decorator IS A and HAS A
-
IS A: we want to be able to treat the decorator as the original component (similar to proxy pattern)
HAS A: we want to be able to send the message downwards and up
Definition
The decorator pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclasses for extending functionality
- Attaches different responsibilities to an object
Originally the object was doing something but now using decorator pattern we attach different responsibilities dynamically at runtime.
- Flexible alternative to sub classing
Perfect for a class explosion scenario
- With decorators we use composition to share behaviors
- We use inheritance (IS A) only to make the decorator behave like the object we try to decorate
INHERITANCE
If we define SubclassA, SubclassB, SubclassC we only have ABC, we can't compose AB or BC at runtime
DECORATORS
With decorators we define: DecoratorA, DecoratorB and DecoratorC and we can compose A and B or B and C at the same time
- Inheritance is not for code reuse
- Inheritance is not for sharing behaviur