Decorator Pattern with special decorator methods in Java

Using the coffee decorator example shown on Wikipedia ( http://en.wikipedia.org/wiki/Decorator_pattern ), how is it possible for someone to have methods that only decorators have, for example, a milk decorator can have a method called "fatContent". Is this possible with this type of design? If not, which template can I use for this?

+6
source share
3 answers

The decorator’s drawing, by definition, does not allow you to add methods other than those defined in the interface. In fact, you can always add methods to any class, but once these methods are not defined in the implementation interface, the client cannot call them using this interface.

A simple solution to your problem is to define several interfaces, for example. Coffee and milk. Then you can define a Capuchino class that implements both interfaces and probably contains 2 instances: SimpleCofee and FoamedMilk . But this solution is more like a combination of Decorator and Facade.

+3
source

You could, but you would need to know the type in order to actually call the method (in the absence of reflection, etc.) if it does not match the type that you are passing.

Types determine what is known at compile time: if CoffeeDecorater does not include the fatContent signature, nothing receiving CoffeeDecoractor knows which method exists.

You can create an additional interface, but you need to either know that it exists so that you can verify it ( instanceof ), or interrogate the class to verify the specific signature (reflection).

Java either knows that the method exists at compile time, or checks it at run time.

+9
source

Decorators can have any number of specific methods. You can introduce a special decorator interface, which decorators implement in addition to the implementation of the decorated interface.

However, someone should know that these methods exist, so either the decorator must call the method inside, the caller must know that he uses the decorator instead of the decorated object (you can test with instanceof ) or use reflection to test these methods.

+4
source

Source: https://habr.com/ru/post/904534/


All Articles