In book 'Head first design patterns', decorator chapter, it talks about issues when decorator deals with concrete type and cause problems. I am copying some Q&A in the chapter:
Q: I’m a little worried about code that might test for a specfic concrete component – say, HouseBlend – and do something, like issue a discount. Once I’ve wrapped the HouseBlend with decorators, this isn’t going to work anymore.
A: That is exactly right. If you have code that relies on the concrete component’s type, decorators will break that code. As long as you only write code against the abstract component type, the use of decorators will remain transparent to your code. However, once you start writing code against concrete components, you’ll want to rethink your application design and your use of decorators.
Could someone give simple examples on what it means that 'client' code is written against concrete type vs abstract type? And how the former cause trouble for decorator?
A sample test code of decorator in the book is like this:
public class StarbuzzCoffee {
public static void main(String args[]) {
Beverage beverage2 = new DarkRoast();
beverage2 = new Mocha(beverage2);
beverage2 = new Mocha(beverage2);
beverage2 = new Whip(beverage2);
System.out.println(beverage2.getDescription()
+ “ $” + beverage2.cost());
...
}
}
Is this test code(also a client code) written against abstract type?
Thanks,
They're talking about code that checks the type of beverage2, for example
if (beverage2 instanceof DarkRoast) {
<do_something>
}
Once you decorate beverage2 with a Mocha or Whip, it isn't a DarkRoast anymore.
Edit: I should also mention that often the use of instanceof
indicates a poor design that doesn't use OO to its fullest, that said it is useful in some cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With