Ornament design?
I have been doing some research on decorator pattern and there is a little confusion about understanding one of the problems. I keep reading that "decorators are usually transparent to the client of the component, that is, unless the client is relying on a particular concrete type of component." I'm not sure what that means - for example, if we have a Beverage class and a Coffee subclass, does that mean the client relies on coffee, and if it was decorated there would be some problems?
source to share
Yes exactly. If you are relying on implementations rather than abstractions (abstract classes or interfaces) this will be a major problem for anyone looking to add an intermediate decorator.
Please refer to the Dependency Inversion Principle in Solid Principles .
Here's a general rule at its core:
need to "depend on abstractions. not depend on nodules"
source to share
Consider the code:
public class StarbuzzCoffee {
public static void main(String args[]) {
Beverage beverage = new DarkRoast();
beverage = new Mocha(beverage);
beverage = new Coffee (beverage);
beverage = new Whip(beverage);
System.out.println(beverage.getDescription()
+ " $" + beverage.cost());
...
}
}
Here Mocha
, Whip
and Coffee
are concrete classes, and Beverage
are an abstract type. Now your styling is great because the client ultimately depends on Beverage
(abstract type).
Now consider a client with code like:
if (beverage instanceof Mocha) {
<do_something>
}
else if (beverage instanceof Coffee ) {
<do_something>
}
You have a problem here because the client has specific behavior for different specific types.
Since we want to depend on asbtraction and not a specific type, we use the concept of dependency injection (code depends on abstract types) in popular frames like Spring. You can read more about IOC
and DI
in this article from martin Fowler.
I hope he explains that "decorators are usually transparent to the client of the component, that is, unless the client is relying on a particular type of component "
On the side, the note instanceof
is bad design that doesn't use OO for the most complete and should be avoided.
source to share