what is the chain? it’s a behavioral design pattern. it deals with how objects make requests and...

25

Post on 19-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

What is the Chain?

• It’s a behavioral design pattern.

• It deals with how objects make requests and how they are handled.

Question

• When an object makes a request, who handles it?

Conventional Approach

• The object that makes the request sends it directly to the object what handles it.

Drawbacks

• Objects must know who handles each type of request.

• Objects must have links to many other objects.

Chain Approach

• Objects are arranged in a “chain of responsibility.”

• Requests are passed along the chain until they are handled.

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.

Example:Context Sensitive Help

Suppose:

• User can click any part of the interface to get specific help.

• If no specific help is available, more general information is provided.

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.

Flow of Requests

Implementation

• Each object must have a HandleHelp() method.

• This method either handles the help request or passes it along the chain.

Interaction Diagram

Implementation (cont.)

• We define a HelpHandler class with a HandleHelp() method.

• All other classes are subclasses to HelpHandler.

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.

Class Diagram

Things to Consider

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.

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.

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.

Pros and Cons

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.

Cons

• Care must be taken to ensure all requests are handled properly.

References

• Gamma, Erich et al. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley, 1995.

Questions?