The Chain of Responsibility

Intent: 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 (Gamma et al., 1994).

Example: A provider of retirement accounts and mutual funds could provide a web-based service allowing their customers to check on the current status of their investments on demand. The customers would be interested in knowing the most up-to-date information on how the stocks, bonds, and other instruments in their fund are currently priced by the market.

If there are several strategic partners that might be able to resolve a given financial symbol and “the right one” might change unpredictably, a chain of responsibility could be implemented to allow the request to flow from one provider to another until the answer is found.

images

Figure 5: Chain of responsibility example diagram.

Qualities and Principles: Each member of the chain is focused on one version of the request. The clients are coupled only to the service interface. The number of services, their implementation details, how they are selected, and the order in which they are given a chance to handle the request are all encapsulated. New services can seamlessly be added, removed, and reordered within the chain. All potential redundancies can be pulled up into the base class. Dependencies between the services (e.g., service Y should only be attempted if service X does not apply) are inherently captured in the ordering of the chain.

Testing: Tests can be made subclasses of the service objects. Each service object can have two tests: one proving the object selects when it should, and another proving the selected behavior is correctly implemented. The ordering of the chain can be tested against the factory that builds it.

Questions and Concerns: What should happen if none of the objects in the chain can complete the request? This is a decision to be made on a case-by-case basis and should be considered early in the design process. The typical implementation of the chain of responsibility is a linked list, but, in fact, any collection can be used and scanned in any way desired. A template method (see p. 54), getValue() in the example, is typically used to implement this pattern internally to keep the “next” pointer private and to avoid redundantly implementing the “handoff to the next object” action.

For more information: https://tinyurl.com/yyfdbko5

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.247.68