Download presentation
Presentation is loading. Please wait.
2
What is the Chain? It’s a behavioral design pattern. It deals with how objects make requests and how they are handled.
3
Question When an object makes a request, who handles it?
4
Conventional Approach The object that makes the request sends it directly to the object what handles it.
5
Drawbacks Objects must know who handles each type of request. Objects must have links to many other objects.
6
Chain Approach Objects are arranged in a “chain of responsibility.” Requests are passed along the chain until they are handled.
7
Advantages Objects don’t care who handles their request. Objects only need one link, to their successor in the chain. Multiple objects have a chance to handle requests.
8
Example: Context Sensitive Help
9
Suppose: User can click any part of the interface to get specific help. If no specific help is available, more general information is provided.
10
Use the Chain Pattern! When the user wants help, the object he clicks on sends a request down the chain. If an object in the chain can provide the needed help, it handles the request. Otherwise, it passes the request to its successor.
11
Flow of Requests
12
Implementation Each object must have a HandleHelp() method. This method either handles the help request or passes it along the chain.
13
Interaction Diagram
14
Implementation (cont.) We define a HelpHandler class with a HandleHelp() method. All other classes are subclasses to HelpHandler.
15
Implementation (cont.) By default, the HandleHelp() method passes the request to the next object in the chain. If an object is to handle a request, HandleHelp() must be overloaded.
16
Class Diagram
17
Things to Consider
18
When to Use the Chain If a request may be handled my multiple objects. If the handler isn’t know ahead of time. If you don’t want to explicitly specify the handler.
19
Linking Objects Existing links between objects may be used if they fit your desired chain. OR Designated links can be included in the handler class.
20
Request Types Request types can be hard coded in the handler class. OR A parameter can be passed to indicate the type of request and how it should be handled.
21
Pros and Cons
22
Pros Coupling between objects is reduced. Sender and receiver of request need no explicit knowledge of one another. Chain allows flexibility in assigning responsibilities to objects.
23
Cons Care must be taken to ensure all requests are handled properly.
24
References Gamma, Erich et al. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, 1995.
25
Questions?
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.