In the Chain of Responsibility Pattern, objects using and implementing an interface (one or more methods) are intentionally loosely coupled. A set of objects that implement the interface are organised in a list (or in rare cases a tree). Objects using the interface make requests from the first implementor object. It will decide whether to perform any action itself and whether to pass the request further down the line in the list (or tree). Sometimes a default implementation for some request is also coded into the pattern if none of the implementors respond to the request.
In this example, the script sends requests to the
lister object. The
lister points to a
UnixLister object. If it can't handle the request, it sends the request to the
WindowsLister. If it can't handle the request, it sends the request to the
The output will be a list of files (with slightly different format depending on the operating system).
Here is a UML representation:
Variations to this pattern:
Lister, to statically type the implementations but because of duck-typing this is optional
if (animal.hasBackbone())delegate to
VertebrateHandlerelse delegate to