I'm just reading up on the Chain of Responsibility pattern and I'm having trouble imagining a scenario when I would prefer its use over that of decorator.
What do you think? Does CoR have a niche use?
I'm just reading up on the Chain of Responsibility pattern and I'm having trouble imagining a scenario when I would prefer its use over that of decorator.
What do you think? Does CoR have a niche use?
Chain
vs
Decorator
I'd say its around the order in which things will happen. If you chain them, the will be called along the chain. With a decorator you're not guaranteed this order, only that additional responsibilities can be attached.
I agree that from structural standpoint this two patterns are very similar. My thought is about the final behavior:
In the classic interpretation of CoR element which handles the request breaks the chain.
If any element in decorator breaks the chain then it will be wrong implementation of decorator, because base part of behavior will be lost. And the idea of decorator is transparent addition of new behavior when the base behavior remains untouched.
Decorator
Decorator pattern allows behaviour to be added to an individual object dynamically.
It provides a flexible alternative to sub classing for extending functionality. Even though it uses inheritance, it inherit from Lowest Common Denominator ( LCD ) interface.
UML diagram for Decorator
Consequences:
Useful links:
When to Use the Decorator Pattern?
Decorator_pattern from wikipedia
decorator from sourcemaking
Chain of responsibility:
UML Diagram
This pattern is more effective when:
Useful links:
Chain-of-responsibility_pattern from wikipedia
chain-of-responsibility-pattern from oodesign
chain_of_responsibility from sourcemaking
Real world example : In a company, a designated role have particular limits to process purchase request. If person with a designated role does not have enough power to approve purchase bill, he will forward the command/request to his successor, who have more power. This chain will continue until the command is processed.
After reading the Gang of Four definitions, I'm not convinced there's a real difference. (included for convenience)
Wikipedia fleshes them out a little, but some of it's kinda arbitrary.
The first two attributes don't really distinguish the patterns. The second two do, but the way Decorator and CoR are usually implemented don't enforce those attributes--the designer just hopes no one writes a Decorator that breaks the chain or a CoRLink that continues the chain after handling the data.
To actually implement these attributes, you'd need something like the following.
Enforced Decorator:
Enforced Chain of Responsibility:
(Alternately, you could just add a line to the javadoc, if all you want is to absolve yourself of the responsibiity in case someone else screws up your design--but why leave it to chance?)