Using the coffee decorator example shown on Wikipedia ( http://en.wikipedia.org/wiki/Decorator_pattern) how would it be possible for someone to be able to have methods that only the decorators have, for example, the milk decorator could have a method called "fatContent". Is this even possible with this type of design pattern? If not, what kind of pattern could I use to accomplish this?
Decorator patterns allow a user to add new functionality to an existing object without altering its structure. So, there is no change to the original class. The decorator design pattern is a structural pattern, which provides a wrapper to the existing class.
Decorator design pattern is one of the structural design pattern (such as Adapter Pattern, Bridge Pattern, Composite Pattern) and uses abstract classes or interface with composition to implement.
Example. The Decorator attaches additional responsibilities to an object dynamically. The ornaments that are added to pine or fir trees are examples of Decorators. Lights, garland, candy canes, glass ornaments, etc., can be added to a tree to give it a festive look.
Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface. Adapter changes an object's interface, Decorator enhances an object's responsibilities.
You could, but you'd need to know the type in order to actually call the method (assuming no reflection etc.) if it doesn't match the type you're passing around.
Types determine what's known at compile time: if CoffeeDecorater
doesn't include a fatContent
signature, nothing receiving a CoffeeDecoractor
knows the method exists.
You could create an additional interface, but you'd need to either know that it existed so you could check for it (instanceof
), or interrogate the class to check for a specific signature (reflection).
Java either knows a method exists at compile time, or checks for it at runtime.
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