Thursday, September 20, 2012

Chain of Responsibility Design pattern

The Chain of Responsibility (CoR) pattern decouples the sender and receiver of a request by interposing a chain of objects between them.

CoR introduction

The Chain of Responsibility pattern uses a chain of objects to handle a request, which is typically an event. Objects in the chain forward the request along the chain until one of the objects handles the event. Processing stops after an event is handled.
Figure 1 illustrates how the CoR pattern processes requests.

Figure 1. The Chain of Responsibility pattern
In Design Patterns, the authors describe the Chain of Responsibility pattern like this:
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

  • You want to decouple a request's sender and receiver
  • Multiple objects, determined at runtime, are candidates to handle a request
  • You don't want to specify handlers explicitly in your code

If you use the CoR pattern, remember:
  • Only one object in the chain handles a request
  • Some requests might not get handled

Those restrictions, of course, are for a classic CoR implementation. In practice, those rules are bent; for example, servlet filters are a CoR implementation that allows multiple filters to process an HTTP request.




No comments:

Post a Comment