Recent changes RSS feed
 

Chain of Responsibility

In Gang of Four (GoF): pass an event of some kind through a sequence of handlers until one is found which can handle the event. Handlers don’t need to know anything about each other and hence can easily be swapped in and out of the chain. Handler-chains can be dynamically created from a central configuration file or by other means.

In the strict GoF definition, the Chain of Responsibility (CoR) pattern encapsulates the logic of choosing what to do with an event much like a switch case. However, CoR is also referred to in a looser sense of passing an event along a chain for processing by multiple handlers. In this case more than one handler - or all - may be activated and the logical “switch-case” behaviour is altered.

Whichever flavour, the power of the pattern lies in the ability to swap loosely-coupled items in and out of the chain without disturbing other code.

The pattern may be a good fit for HTTP request handling. Each http request might map to a handler chain with individual handlers for each possible page type, eg:

User input examination/400 bad request syntax page
        |
       \|/
Authentication/login page
        |
       \|/
Authorisation/401
        |
       \|/
Redisplay form
        |
       \|/
Process form/success page
        |
       \|/
404 reponse

Chain of Responsibility has some similarities to Observer - particularly in the looser sense. Intercepting Filter is a form of CoR. CoR may be most applicable to cases where there are a relatively small number of handlers in the chain.

 
pattern/chain_of_responsibility.txt · Last modified: 2006/12/09 17:14
 
Hosting for this site donated by Procata PHP Development