Java Reference
In-Depth Information
Chain of Responsibility
Pattern Properties
Type: Behavioral
Level: Component
Purpose
To establish a chain within a system, so that a message can either be handled at the level where it is first received,
or be directed to an object that can handle it.
Introduction
The Personal Information manager might be used to manage projects as well as contacts. Think of this as a tree
structure of task objects. One task is the “root” of the tree, representing the project itself. The base task has a set
of subtasks, each subtask has its own set of subtasks, and so on. In this way, you divide a project up into an
increasingly detailed set of related objectives. This gives users the ability to group and organize actions relating to
their objectives, as in the following example:
Project (base task): Own a country
Subtask: Acquire a small fortune
Subtask: Use psychic hotlines to predict winning lottery numbers
Subtask: Research whether the climate is better in the Atlantic or Pacific
Subtask: Locate an island for sale
Subtask: See whether there are any islands for auction on E-Bay
Subtask: Research the U.N. rules for incorporation as a country
Subtask: Decide what to name the country
How do you manage information in a structure like this? For example, it would be helpful to be able to see who is
responsible for a certain set of tasks or deliverables. How do you delegate groups of tasks to someone, or assign
the tasks to someone else?
One option is to define an attribute for each task to represent the owner. When the owner for a task changes, all
tasks and subtasks are updated with the new owner's name. However, this seems like an inefficient way to store a
task owner, requiring much more information to be stored and maintained than you would prefer.
An alternative is to reference one or more central objects that store the task owners. While this approach more
effectively manages memory, it requires a lot of work to manage the links between the tasks and the central
objects used to maintain data.
What happens if you use the task tree itself to manage owners? Define a method for the Task class called
getOwner , associated with an owner attribute. When called, the method checks whether the owner was specified
(not null). If an owner was specified, the name is returned; if not, the task calls the getOwner method for its
parent. This solution requires less work than either of the previous solutions and is still efficient in memory use.
You only need to specify the owner at a single location in the tree. The Task objects themselves do the rest of the
work, delegating the getOwner call to their parent tasks until one is found with the information. This is an
example of the Chain of Responsibility design pattern.
Applicability
Use Chain of Responsibility when:
There is a group of objects in a system that can all potentially respond to the same kind of message.
 
Search WWH ::




Custom Search