Wednesday, May 30, 2012

Behavioral Patterns - 1.Chain of Responsibility

At times we may need to deal with different objects performing different tasks based on a defined workflow. There may be a need for delegation and processing the tasks between various objects.

Such kind of problems can be solved by the "Chain of Responsibility" pattern.

Consider a situtation where we may need to handle the bank loan approval process.A bank may have approving authorties at various levels like Manager,Director,President,etc.

The approval limit may vary across the levels. For Example, a Manager has a maximum approval limit of Rs.10,000, for a Director it will be RS.50,000 and for a President it will be more than RS.50,000.

Whenever a Manager receives a request for approving Rs.1,00,000, he/she will delegate the request to their immediate predecessor. Here it will be delegated to the Director. Since, the requested approval amount exceeds the Directors limit, it will be furthur delegated to the President. The President can approve the amount.

Here, the responsibility of approval is being delegated to various persons based on their nature. This can be termed as "Chain Of Responsibility".

Please refer the below class diagram for more details on this pattern,



Following code snippet can provide a clear idea over the implementation,

 public void approve(double amount) {
  System.out.println("Manager checking the limits");
  if(amount<=10000)
      System.out.println("Approved!");
  else{
     System.out.println("Approval Limit Exceeds! Delegating to "+predecessor);
     predecessor.approve(amount); //Delegating the responsibility to the predecessor
  }


Code snippet for the client could be,
 
  Approver president=new President(null);
  Approver director=new Director(president);
  Approver manager=new Manager(director);
  manager.approve(200000);

No comments:

Post a Comment