Monday, 28 November 2011

JavaEE Revisits Design Patterns: Observer

Aside from being implemented in many languages and many applications, Observer Pattern has been a part of Java since version 1.0. Observer Pattern is also a good implementation of Hollywood Principle. Just like Agents in Hollywood like to callback the candidates for a role instead of being called daily to be asked about available jobs, most of the server side resources like the push the available data to the appropriate client instead of being asked for updates on a time interval.

Such time interval queries can be both consuming to much resource on the server and also cause more network traffic than actually needed. Although Java had support for Observer Pattern since day 0, it is always argued to be not the best implementation (Have a look at Observer and Observable). Being on JavaEE world may even complicate things. However JavaEE6 comes with an alternative.

JavaEE6 offers '@Observable' annotation as an easy out of box implementation of Observer Pattern. Lets visit the previous post and extend it to use observers.

package com.devchronicles.observer;


import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;


/**
 *
 * @author Murat Yener
 */
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService {
    @Inject
    private String message;
    
    @Inject 
    Event<String> event;
    
    public void startService(){
        System.out.println("start service call "+message);
        event.fire("this is my "+message);
        System.out.println("done...");
    }
}


The EventService class will be injected an Event object of type String which can be used to fire String objects. If you had not read the previous post,  message object is a String which will be produced by a factory and injected to the EventService class. To make it simpler you can just type any string constant to the variable called message.

Since we are already done with the observable part, now it is time to create an observer to listen our events.

package com.devchronicles.observer;


import javax.ejb.Stateless;
import javax.enterprise.event.Observes;


/**
 *
 * @author Murat Yener
 */
@Stateless
public class EventObserver {


    public void doLogging(@Observes String message){
        System.out.println("Observed:"+message);
    }
}

The Observes annotation marks the method as an observer for fired String events. If you run the server and fire up start service method, you will realize how magically a string will be injected to EventService class and than fired where it will be caughed (observed) by EventObserver class. Surprisingly that is all you need to implement the observer pattern in JavaEE6.

No comments:

Post a Comment