JavaEE Revisits Design Patterns: Decorator

This time last year I wrote a series of blog posts on JavaEE implementation of design patterns. Roughly after a year, I realized I missed my favorite pattern, the decorator.

Decorator pattern is basically a way to extend functionality of an object by decorating with other objects which can wrap the target object and add their own behavior to it. If you never used or heard of decorators, I highly recommend reading chapter 3 of Head First Design Patterns.

Pretty much like other patterns mentioned in my posts before, JavaEE has an easy an elegant way to use the decorator pattern. Lets start with a simple stateless session bean.

package com.devchronicles.decorator;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

/**
 *
 * @author murat
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService {

    public void startService(){
        System.out.println("do something important here...");
    }
}

To start implementing the decorator pattern, we need an interface so we can bind the decorators and the object to be decorated together.

package com.devchronicles.decorator;

/**
 *
 * @author murat
 */
public interface ServiceInterface {
    public void startService();
}

The interface has the method which the decorators will add functionality on. Next we need some changes on our existing EventService bean to make it decoratable.

package com.devchronicles.decorator;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

/**
 *
 * @author murat
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService implements ServiceInterface{

    public void startService(){
        System.out.println("do something important here...");
    }
}

Now we are ready to add as much as decorator we need. All we need to do is to annotate our class, implement the ServiceInterface and to inject our service delegate.

package com.devchronicles.decorator;

import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.inject.Inject;

/**
 *
 * @author murat
 */
@Decorator //declares this class as a decorator
public class DecoratorService implements ServiceInterface{ //must implement the service interface

    @Inject //inject the service
    @Delegate //and annotate as the delegate
    ServiceInterface service;

    @Override
    public void startService() { //implement the startService method to add functionality
        System.out.println("decorating the existing service!");
        service.startService(); //let the execution chain continue
    } 
}

Several decorators can be using the service interface.

package com.devchronicles.decorator;

import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.inject.Inject;

/**
 *
 * @author murat
 */
@Decorator
public class Decorator2Service implements ServiceInterface{
     @Inject
    @Delegate
    ServiceInterface service;

    @Override
    public void startService() {
        System.out.println("decorating the service even further!!!");
        service.startService();
    }
}

Most of the configuration can be done via annotation in JavaEE6. However we still need to add some xml configuration to make decorators work. It might seem disappointing since we already annotated our decorators but still the configuration is pretty simple and needed in order to declare the order of execution. Add the following lines to the empty beans.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
           <decorators>
               <class>com.devchronicles.decorator.DecoratorService</class>
           <class>com.devchronicles.decorator.Decorator2Service</class>
           </decorators>
</beans>

When the startService method of our EventService is executed, the decorators will decorate the ejb and add their own behavior to the execution.

...

INFO: WEB0671: Loading application [Decorator] at [/Decorator]
INFO: Decorator was successfully deployed in 2,534 milliseconds.
INFO: decorating the existing service!
INFO: decorating the service even further!!!
INFO: do something important here...
...

 
Reference: JavaEE Revisits Design Patterns: Decorator from our JCG partner Murat Yener at the Developer Chronicles blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "JavaEE Revisits Design Patterns: Decorator"

  1. philip bradey says:

    I’m confused about the role of the annotations in DecoratorService. If I simply leave out the @Decorator and @Delegate annotations, how would things be different? As long as DecoratorService implements ServiceInterface, the compiler will oblige to override all of the methods in the delegate so what are these annotations adding?

Leave a Reply


nine − = 5



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books