Quantcast
Channel: Free practice test , mock test, driving test, interview questions » design patterns
Viewing all articles
Browse latest Browse all 10

Chain of Responsibility Design Pattern

$
0
0

Chain of Responsibility Design Pattern

Problem

Consider the case where you have a structural hierarchy of object that is not necessarily subclasses from the same base class. Now lets say there is a piece of functionality that they all can implement, but it is not statically determinate which should handle the case. Now I know that sounds a little complicated, but picture a context sensitive help system. Each piece of the display may have a piece of text that is wants to display when ever the cursor is over top of it, or it may not. In the case where a piece doesn’t want to handle it, you want the class that contains it to display a more general help string. You also want this system to be dynamic at run-time. How can this be done?

Solution

The Chain of responsibility can solve this problem. The chain of responsibility requires that each of the classes involved inherit from a base class, let’s say HelpHandler. Now when they are instantiated, the objects all initialize their parent class with a successor, which is a reference to another object that is also derived from the base class. When the time comes to call the method that you want to pass up the chain, the first object picked is the most appropriate one. If the object doesn’t want (or can’t handle) the request, it calls the BaseClass::Method() which calls the method for the successor, and so on, until one of the objects handles the request.

Consequences

The chain of responsibility makes it so the client doesn’t need know who is in fact handling the request, only that the request is being handled. As well, you can change the hierarchy at run-time to provide for a changing environment. However, it should be noted that in this system all participants in the chain could refuse to handle the request, and the client would not know.


Viewing all articles
Browse latest Browse all 10

Trending Articles