Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator Pattern with decorator specific methods in Java

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?

like image 707
Atrus Avatar asked Dec 27 '11 13:12

Atrus


People also ask

What is the decorator pattern in Java explain it with an example?

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.

What is the decorator pattern in Java Can you give an example of a decorator pattern?

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.

Where do we use Decorator design pattern explain with example?

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.

What is the difference between Adapter vs proxy vs Decorator design patterns?

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.


1 Answers

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.

like image 99
Dave Newton Avatar answered Sep 25 '22 19:09

Dave Newton