Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator Pattern Confusion?

I've been doing some research on the decorator pattern, and there is a bit of confusion with understanding one of it's problems. I keep reading that "decorators are typically transparent to the client of the component; that is, unless the client is relying on the component's concrete type". I'm not sure what this means - for instance if we have a Beverage class, and a Coffee subclass, does this mean that the client relies on Coffee and so if it was decorated, there would be some issues?

like image 977
user3370603 Avatar asked Jul 19 '26 06:07

user3370603


2 Answers

Yes exactly. If you rely on implementations not on abstractions(abstract classes or interfaces), that would be a serious problem for someone/you who wants to add a decorator in between.

Please consult the Dependency inversion principle of Solid Principles.
That's a general rule at its core:

one should “Depend upon Abstractions. Do not depend upon concretions“

like image 178
Jahan Zinedine Avatar answered Jul 20 '26 20:07

Jahan Zinedine


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 is abstract type. Now your decoration is fine becuase client ultimately depends on Beverage (abstract type).

Now consider a client having code like:

if (beverage instanceof Mocha) {
    <do_something>
}
else if (beverage instanceof Coffee ) {
    <do_something>
}

Here you have problem because client is having specific behaviour for different concrete types.

As we want to depend on asbtraction and not concrete type we use concept of dependency injection (code is dependent on abstract types) in popular frameworks like Spring. You can read more about IOC and DI in this article by martin Fowler.

I hope it explains the line "decorators are typically transparent to the client of the component; that is, unless the client is relying on the component's concrete type"

On a side note instanceof is a poor design which does not use OO to fullest and should be avoided.

like image 36
akhil_mittal Avatar answered Jul 20 '26 20:07

akhil_mittal