Design Templates: Decorator Template – Java DZone

The decorator model is one of the structural models of GoF and dynamically adds logic to an object. Instead of inheritance, the decorator adds functionality at runtime. They introduce great flexibility.

In the typical implementation, the decorator and the target object must implement the same interface. The decorator wraps the target object and adds its own behavior.

public class PriceDiscountDecorator implements Product {

 private Product product;

 public String generateLabel() {
 product.setPrice(product.getPrice() * 0.5);
 return product.generateLabel();

The model implementation relies on the delegate and the decorator implementing the same interface. The delegate is encapsulated and specific logic implemented for each of the interface methods.

The CDI container injects any available instance of a concrete instance of the Product interface into the Product member variable.

When a call is made to the generateLabel method of any instance of Product, the container intercepts it. The call is delegated to the generateLabel method of the PriceDiscountDecorator, where it reduces the price of the product and forwards the call to the original destination by calling the generate Label method of the destination Product times.

Annotate with a qualifier the class you want to decorate and the instance variable in the decorator and only instances of these classes will be injected into the decorator.

The order in which the decorators are called is specified in an XML file or by setting an interceptor priority. Decorators with lower priority are called first.

The good, the bad and the ugly


It is very easy to change the behavior without breaking the legacy code.

The bad

It may require XML configuration (

The ugly one

As always, overuse will introduce a hard-to-follow flow of execution.

Source link

Previous Angular JS Tutorial - MVC and MVVM Design Templates
Next Design Templates: Factory Template - Java DZone

No Comment

Leave a reply

Your email address will not be published. Required fields are marked *