Wednesday, March 10, 2010

Chain of Responsibility Pattern

A pattern recommends a low degree of coupling, mainly used when there is more than one object that can handle or fulfill a client request, and that request in some sequential order

Each object having a pointer to the next object in the chain, object receives the request decides either to handle the request or to pass it on to the next object

 

Characteristics of the CoR pattern:

  • Request handler objects and the order decided dynamically at runtime by the client.
  • All potential handler objects should provide a consistent interface.
  • Neither the client object nor any of the handler objects in the chain need to know which object will actually fulfil the request.
  • Request may not be fulfilled even after reaching the end of the chain.

EXAMPLE:

Purchase request (PR) authorization process, PR needs to be authorized, organization with four levels of management personnel

 

Management Level

Authorization Limit

HandlerA

$25,000

HandlerB

$100,000

HandlerC

$200,000

HandlerD

$400,000

 

Each of the four classes representing different levels of management is a potential handler for a given PR and hence it is not advisable to tie a PurchaseRequest instance to any of the handlers (That's why you can't use the observer pattern to solve this problem).

Link to The example is HERE