Tuesday, 6 December 2011

JavaEE Revisits Design Patterns: Observer Part 2

As seen in the previous post, JavaEE6 offers an easy way to implement the Observer Pattern. After publishing the post, I had receive few questions on how to differentiate string types that are fired and observed.

Although in real world scenarios you wouldn't probably firing and observing plain strings but your own objects which would be observed by their type, still it is pretty easy to differentiate same type of objects and setup different observers to listen them.

First lets start with the part to differentiate plain strings.


package com.devchronicles.observer;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;


/**
 *
 * @author Murat Yener
 */

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.PARAMETER})
public @interface MyEvent {
    
    Type value();
    
    enum Type{
        LOGGING, MESSAGE
    } 
}

The interface above will act as annotation to mark the string to be fired and later to be observed just by annotating the appropriate parts.

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 @MyEvent(MyEvent.Type.LOGGING)
    Event<String> event;


    @Inject @MyEvent(MyEvent.Type.MESSAGE)
    Event<String> anotherEvent;

    
    public void startService(){
        System.out.println("start service call "+message);
        event.fire("this is my "+message);
        System.out.println("done...");
        anotherEvent.fire("done with the service!");
    }
}

We just add MyEvent annotation with the desired type and later fire the events as we did before. The parts marked with red is all we added to the example in the previous post.

Now lets annotate the observer part. Again We will be just adding the red parts to the previous example.

package com.devchronicles.observer;

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

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

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



    public void doLogging(@Observes @MyEvent(MyEvent.Type.MESSAGE) String message){
        System.out.println("Observed another type of message:"+message);
    }

}

That would be all you would need to differentiate even the same type of objects to observe.

No comments:

Post a Comment