Design Pattern : Chain of Responsibility
Before getting into the definitions, I can tell you one simple example that can give you enough understanding on Chain of Responsibility pattern, For example, Let’s take the below problem,
An order entry will be created in the database once user adds line-items and also a mail will be sent to the customer and a mail to admin dept. of the store. Once the order is received by admin. dept. the order detail will be sent for approval to Store Supervisor. But there are certain products jewels, ornaments can be only approved by Store Head, whereas, the products like Shoes, Pencils can be approved by Section Head himself.
This is a simple and a well known requirement. If you look details of the requirement, following are behaviors we need to keep in our mind :-
- if order needs to be created you might need to check the inventory for all the line items
- for each line item,
- we need to make sure whether that item can be ordered in first hand,
- if it can be ordered, then we need to inform the appropriate approving authorities
- and wait until we receive approvals from them
- if we don’t receive approvals with in certain time,
- send a mail to customer that order is in hold and not yet processed
- and also send a mail to admin. dept. that an order is moved into hold because of no feed back (or response from so and so approving authority)
- if we don’t receive approvals with in certain time,
- upon the successful creation of order we should send the mail to customer as well as admin. dept that the order is successfully created now it can be then processed for shipment (or whatsoever)
Looks like we went into very much details!. But, anyway, we are not going to implement the entire requirement here. But we will try to develop the code/method signatures that can obey Chain of Responsibility rules.
Let’s talk some theory here, because we need to understand little bit before we proceed to solve the problem. In the pattern terms, here is what have,
- Context is something that defines a platform for a request. So, as per our example
- ConcreteHandler handles the request and if it cannot satisfy the request it passes the request to its Successor or Predecessor (A,B,C,D)
( continues .. )
