Java Design Patterns Chain of Responsibility Patterns

Introduction

Chain of Responsibility Patterns avoid coupling the sender to its receiver.

Chain of Responsibility Patterns chain the receiving objects and pass the request along the chain until an object handles it.

Use case

  • Use various handlers for mouse event based on mouse cursor position.

Example

enum EventPriority {
   Normal, High//  www .jav a  2s  .  co m
}
interface ActionListener {
   Boolean actionPerformed(Event msg);
}

class Event {
   public String Text;
   public EventPriority Priority;

   public Event(String msg, EventPriority p) {
      Text = msg;
      this.Priority = p;
   }
}


class Button {
   public ActionListener listener;

   public Button(ActionListener firstReceiver) {
      this.listener = firstReceiver;
   }

   public void RaiseEvent(Event msg) {
      if (listener != null)
         listener.actionPerformed(msg);
   }
}

class FaxErrorHandler implements ActionListener {
   private ActionListener listener;

   public FaxErrorHandler(ActionListener nextReceiver) {
      listener = nextReceiver;
   }

   public Boolean actionPerformed(Event msg) {
      if (msg.Text.contains("Fax")) {
         System.out.println("FaxErrorHandler processed " + msg.Priority + "priority issue: " + msg.Text);
         return true;
      } else {
         if (listener != null)
            listener.actionPerformed(msg);
      }
      return false;
   }
}

class EmailErrorHandler implements ActionListener {
   private ActionListener listener;

   public EmailErrorHandler(ActionListener nextReceiver) {
      listener = nextReceiver;
   }

   public Boolean actionPerformed(Event msg) {
      if (msg.Text.contains("Email")) {
         System.out.println("EmailErrorHandler processed " + msg.Priority + "priority issue: " + msg.Text);
         return true;
      } else {
         if (listener != null)
            listener.actionPerformed(msg);
      }
      return false;
   }
}

public class Main {
   public static void main(String[] args) {
      ActionListener faxHandler, emailHandler;

      emailHandler = new EmailErrorHandler(null);

      faxHandler = new FaxErrorHandler(emailHandler);

      Button raiser = new Button(faxHandler);

      Event m1 = new Event("Fax", EventPriority.Normal);
      Event m2 = new Event("Email", EventPriority.High);
      Event m3 = new Event("User", EventPriority.Normal);
      Event m4 = new Event("Network", EventPriority.High);

      raiser.RaiseEvent(m1);
      raiser.RaiseEvent(m2);
      raiser.RaiseEvent(m3);
      raiser.RaiseEvent(m4);

   }
}



PreviousNext

Related