Java Reference
In-Depth Information
Chapter 12. Chain of Responsibility
Object-oriented developers strive to keep objects loosely coupled, keeping the responsibility
between objects specific and minimal. This lets you introduce change more easily and with
less risk of introducing defects. To a degree, decoupling occurs naturally in Java. Clients see
only an object's visible interface and remain isolated from the details of the object's
implementation. This arrangement, however, leaves in place the fundamental coupling that
the client knows which object has the method the client needs to call.
An opportunity to loosen the restriction that a client must know which object to use occurs
when you can arrange the objects in chains. In such a case, you can provide these objects with
an operation that each object either performs or passes along the chain. The intent of
the C HAIN OF R ESPONSIBILITY pattern is to avoid coupling the sender of a request to its
receiver by giving more than one object a chance to handle the request. To apply this pattern,
chain the receiving objects and pass the request along the chain until an object handles it.
Varieties of Lookup
In C HAIN OF R ESPONSIBILITY , an object model takes on the job of finding which object can
satisfy a client's request. This approach goes beyond the two lookup mechanisms that are built
into Java: exception handling and method lookup.
When an exception is thrown, the Java interpreter looks back up the call stack to find
a method called from a block enclosed in a try/catch statement. If this try/catch
statement does not catch an exception of the type thrown, the Java interpreter keeps looking.
This can propagate up to the main() method. If the exception is not handled there, the Java
interpreter prints out an error message and stack trace and then exits.
The more common case of lookup in Java is method lookup —the algorithm for deciding
which definition of a method to use when a client calls an object's method. For example, if
you call an object's toString() method, Java will use the method's implementation that
appears lowest in the object's class hierarchy. When the compiler cannot make this
determination in advance, the Java interpreter looks up the right method to invoke, at runtime.
CHALLENGE 12.1
How does the C HAIN OF R ESPONSIBILITY pattern differ from ordinary method
lookup?
Refactoring to Chain of Responsibility
The Oozinoz application suite includes a visualization that shows machines on the factory
floor. The visualization includes the ability to select multiple items and to pop up a menu of
various requests. One item on the pop-up menu displays a list of the engineers who are
responsible for the selected equipment. The simulated items include machines, machine
composites, tools, and tool carts. Tools are always assigned to tool carts, and tool carts have a
responsible engineer. In determining who is responsible for the machine, machines may have
Search WWH ::




Custom Search