Caveats

The Decorator design pattern is great because it lets us compose objects on the fly. Using Kotlin's by keyword will make it simple to implement. But there are still limitations that you need to take care of.

First, you cannot see inside of the Decorator:

println(sadHappy is SadMap<*, *>) // True

That's the top wrapper, so no problem there:

println(sadHappy is MutableMap<*, *>) // True

That's the interface we implement, so the compiler knows about it:

println(sadHappy is HappyMap<*, *>) // False

Although SadMap contains HappyMap and may behave like it, it is not a HappyMap! Keep that in mind while performing casts and type checks.

Second, which is related to the first point, is the fact that since Decorator is usually not aware directly of which class it wraps, it's hard to do optimizations. Imagine that our CTO requested SuperSadMap to print Okay... Okay... and that's it, on the same line. For that, we would need to either capture the entire output, or investigate all the classes that we will wrap, which are quite complex tasks. 

Keep these points in mind when you use this powerful design pattern. It allows for adding new responsibilities to an object dynamically (in our case, printing Yay is a responsibility), instead of subclassing the object. Each new responsibility is a new wrapping layer you add.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.235.79