Like Us

Monday 17 September 2012

Java Event Delegation Model


Java Event Delegation Model : Example using Core Java.


Event Delegation model is just a mechanism of broadcasting an event.

There are basically 3 entities involved in event delegation model.
  • Event - It is an element which describes the event.
  • Event source - It is an element which generates the event and sends it to the listener.
  • Event listener  - It is an element which receives the event sent by the source and executes a specific functionality with respective to the event.



Here are the basic classes responsible for complete Event Delegation model mechanism,


Event.java

package com.capitalcode.events;

/**
 * The Class Event.
 */
public class Event {

 /** The Constant serialVersionUID. */
 private static final long serialVersionUID = 1L;
 
 /** The event name. */
 private String eventName;
 
 /** The event source. */
 private EventSource eventSource;
 
 /** The data. */
 private Object data;

 /**
  * Instantiates a new event.
  *
  * @param eventName the event name
  * @param eventSource the event source
  * @param data the data
  */
 public Event(String eventName, EventSource eventSource, Object data) {
  this.eventName = eventName;
  this.eventSource = eventSource;
  this.data = data;
 }

 /**
  * Gets the event name.
  *
  * @return the event name
  */
 public String getEventName() {
  return eventName;
 }

 /**
  * Gets the event source.
  *
  * @return the event source
  */
 public EventSource getEventSource() {
  return eventSource;
 }

 /**
  * Gets the data.
  *
  * @return the data
  */
 public Object getData() {
  return data;
 }

}

EventSource.java

package com.capitalcode.events;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * The Class EventSource : This class is responsible for sending the events to its registered Listeners.
 */
public class EventSource {
 
 /** The Constant serialVersionUID. */
 private static final long serialVersionUID = 1L;
 
 /** The map listener list which will store the registered listeners to this source for a specific event denoted by event name. */
 protected Map<String, List<EventListener>> mapListenerList = new HashMap<String, List<EventListener>>();

 /**
  * Adds the event listener.
  *
  * @param eventName the event name
  * @param listener the listener
  */
 public void addEventListener(String eventName, EventListener listener) {
  if(mapListenerList.get(eventName) == null){
   List<EventListener> listenerList = new ArrayList<EventListener>();
   mapListenerList.put(eventName, listenerList);
  } 
  
  List<EventListener> listenerList = mapListenerList.get(eventName);
  if(!listenerList.contains(listener)){
   listenerList.add(listener);
  }
 }

 /**
  * Removes the event listener.
  *
  * @param eventName the event name
  * @param listener the listener
  */
 public void removeEventListener(String eventName, EventListener listener) {
  if(mapListenerList.get(eventName) != null && mapListenerList.get(eventName).size() > 0){
   mapListenerList.get(eventName).remove(listener);
  } 
 }
 
 /**
  * Checks if is listener available.
  *
  * @param eventName the event name
  * @return true, if is listener available
  */
 public boolean isListenerAvailable(String eventName){
  return !(mapListenerList.get(eventName) == null || mapListenerList.get(eventName).size() == 0); 
 }

 /**
  * Fire event.
  *
  * @param event the event
  */
 final void fireEvent(Event event) {
  List<EventListener> listenerList = mapListenerList.get(event.getEventName());
  
  if(isListenerAvailable(event.getEventName())){
   for (EventListener eventListener : listenerList) {
    eventListener.onEvent(event);
   }
  }
  
 }
}

EventListener.java

package com.capitalcode.events;

import java.io.Serializable;


/**
 * The listener interface for receiving event events.
 * The class that is interested in processing a event implements this interface, 
 * and the object created with that class is registered with a component using the
 * component's <code>addEventListener<code> method. When
 * the event event occurs, that object's appropriate
 * method is invoked.
 *
 * @param <T> the generic type
 * @see EventEvent
 */
public interface EventListener<T extends Event> extends Serializable {
 
 /**
  * On event.
  *
  * @param event the event
  */
 public void onEvent(T event);
}

Events.java

package com.capitalcode.events;

/**
 * The Class Events.
 */
public class Events {
 
 /** The Constant serialVersionUID. */
 private static final long serialVersionUID = 1L;
 
 /**
  * Send event.
  *
  * @param e the event object 
  */
 public static void sendEvent(Event e){
  e.getEventSource().fireEvent(e);
 }
}

Below code will simulate the above scenario

package com.capitalcode.events;

/**
 * The Class EventTest.
 */
public class EventTest {
 
 /**
  * The main method.
  *
  * @param args the arguments
  */
 public static void main(String[] args){
  
  //Simulated Code for getting the Order from database
  final Order order = getOrderFromDB();
  
  //We have registered on event named ON_DISPATCHED on the order.
  //When Order status will be changed to DISPATCHED, this code will get executed 
  order.addEventListener("ON_DISPATCHED", new OrderEventListener());
  
  //Change status the DISPATCHED
  //At this time OrderEventListener.onEvent() method will get executed
  order.setOrderStatus(Order.OrderStatus.DISPATCHED);
 }
 
 
 /**
  * Gets the order from database.
  *
  * @return the order from retrieved from database
  */
 public static Order getOrderFromDB(){
  Order order = new Order();
  order.setCustomerId(101);
  order.setOrderId(123);
  order.setOrderItems(new String[]{"Pen Drive","CD"});
  order.setOrderStatus(Order.OrderStatus.ORDERED);
  return order;
 }
}


/**
 * The Class OrderEventListener : Event Listener.
 */

class OrderEventListener implements EventListener<Event>{
 
 private static final long serialVersionUID = 1L;

 //Method Executed when the order status is changed to DISPATCHED
 public void onEvent(Event event) {
  
  if(((Order)event.getEventSource()).getOrderStatus().equals(Order.OrderStatus.DISPATCHED)){
   //If order status is DISPATCHED executed the code for sending the mail to customer
   System.out.println("Send a Mail to Customer");
  }
 }
}


/**
 * The Class Order : Event Source.
 */

class Order extends EventSource{
 private long orderId;
 private long customerId;
 private String[] orderItems;
 private OrderStatus orderStatus;

 public long getOrderId() {
  return orderId;
 }

 public void setOrderId(long orderId) {
  this.orderId = orderId;
 }

 public long getCustomerId() {
  return customerId;
 }

 public void setCustomerId(long customerId) {
  this.customerId = customerId;
 }

 public String[] getOrderItems() {
  return orderItems;
 }

 public void setOrderItems(String[] orderItems) {
  this.orderItems = orderItems;
 }

 public OrderStatus getOrderStatus() {
  return orderStatus;
 }

 public void setOrderStatus(OrderStatus orderStatus) {
  this.orderStatus = orderStatus;
  if(orderStatus.equals(OrderStatus.DISPATCHED)){
   //When Order Status is DISPATCHED send the event to respective listeners 
   Events.sendEvent(new Event("ON_DISPATCHED", this, null));
  }
 }


 enum OrderStatus{
  ORDERED,DISPATCHED,RECEIVED;
 }
}


0 comments:

Post a Comment