Design Patterns & Refactoring
Chain of Responsibility
Oliver Haase
HTWG Konstanz
Oliver Haase (HTWG Konstanz) Design Patterns & Refactoring 1 / 9
Description
Classification: Object-based behavioral pattern
Purpose: Build a chain of possible receivers of a request. Delegate request along the chain until one receiver handles it.
Motivation
Imagine a context-sensitive help system for a GUI
Each graphical component may (or may not) have associated with it a help text.
On, e.g., right mouse click, the most specific help text of the clicked-on component is displayed to the user.
aPrintButton aMouseListener
handleHelpReq
aPrintDialog
handleHelpReq
aTopLevelContainer
handleHelpReq
Oliver Haase (HTWG Konstanz) Design Patterns & Refactoring 3 / 9
Idea
Chain-up potential receivers in descending order from most specific to least specific
Upon reques, each receiver can decide to handle it ot to propagate it to its successor.
Description
Applicability: Use the chain-of-responsibility pattern if
several objects could handle a request, and it is unknown at development time which one actually will.
the set of possible receivers is to be configured dynamically
Oliver Haase (HTWG Konstanz) Design Patterns & Refactoring 5 / 9
Structure
Client
+ handleRequest() Handler
+ handleRequest() ConcreteHandler1
+ handleRequest() ConcreteHandler2
successor
Consequences
Loose Coupling: the chain-of-responsibility pattern decouples the sender of a request from the receiver.
No Processing Guarantee: Because each receiver may decide notto handle a request, it might fall off the chain unprocessed.
Oliver Haase (HTWG Konstanz) Design Patterns & Refactoring 7 / 9
Implementation
The successor chain can
either use a pre-existing linkage of the receiver objects, or be built separately.
Related Patterns
Composite:
Often, the parent object of a composite is used as the successor object for a chain of responsibility.
Oliver Haase (HTWG Konstanz) Design Patterns & Refactoring 9 / 9