Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Professional C++ [eng].pdf
Скачиваний:
284
Добавлен:
16.08.2013
Размер:
11.09 Mб
Скачать

Chapter 26

The output of this program will be:

<B>A party? For me? Thanks!</B> <I><B>A party? For me? Thanks!</B></I>

There is an interesting side effect of this implementation that just happens to work correctly for HTML. If you applied the same style twice in a row, the effect would only occur once:

cout << BoldParagraph(BoldParagraph(p)) .getHTML() << endl;

The result of this line is:

<B>A party? For me? Thanks!</B>

If you can see the reason why, you’ve mastered C++! What’s happening here is that instead of using the BoldParagraph constructor that takes a const Paragraph reference, the compiler is using the built-in copy constructor for BoldParagraph! In HTML, that’s fine — there’s no such thing as double-bold.

However, other decorators built using a similar framework may need to implement the copy constructor to properly set the reference.

The Chain of Responsibility Pattern

A chain of responsibility is used when you want each class in an object-oriented hierarchy to get a crack at performing a particular action. The technique generally employs polymorphism so that the most specific class gets called first and can either handle the call or pass it up to its parent. The parent then makes the same decision — it can handle the call or pass it up to its parent. A chain of responsibility does not necessarily have to follow a class hierarchy, but it typically does.

Chains of responsibility are perhaps most commonly used for event handling. Many modern applications, particularly those with graphical user interfaces, are designed as a series of events and responses. For example, when a user clicks on the File menu and selects Open, an open event has occurred. When the user clicks the mouse on the drawable area of a paint program, a mouse down event occurs. As the shape is drawn, mouse move events continually occur until the eventual mouse up event. Each operating system has its own way of naming and using these events, but the overall idea is the same. When an event occurs, it is somehow communicated to the program, which takes appropriate action.

As you know, C++ does not have any built-in facilities for graphical programming. It also has no notion of events, event transmission, or event handling. A chain of responsibility is a reasonable approach to event handling because in an object-oriented hierarchy, the processing of events often maps to the class/subclass structure.

Example: Event Handling

Consider a drawing program, which has a hierarchy of Shape classes, as in Figure 26-7.

776

Applying Design Patterns

Shape

Square

Circle

Triangle

Figure 26-7

The leaf nodes handle certain events. For example, Square or Circle can receive mouse down events that will select the chosen shape. The parent class handles events that have the same effect regardless of the particular shape. For example, a delete event is handled the same way, regardless of the type of shape being deleted. The ideal algorithm for handling a particular event is to start at the leaf nodes and walk up the hierarchy until the message is handled. In other words, if a mouse down event occurs on a Square object, first the Square will get a chance to handle the event. If it doesn’t recognize the event, the Shape class gets a chance. This approach is an example of a chain of responsibility because each subclass may pass the message up to the next class in the chain.

Implementation of a Chain of Responsibility

The code for a chained messaging approach will vary based on how the operating system handles events, but it tends to resemble the following code, which uses integers to represent types of events.

void Square::handleMessage(int inMessage)

{

switch (inMessage) {

case kMessageMouseDown: handleMouseDown(); break;

case kMessageInvert:

handleInvert();

break;

default:

// Message not recognized--chain to superclass Shape::handleMessage(inMessage);

}

}

void Shape::handleMessage(int inMessage)

{

switch (inMessage) { case kMessageDelete:

handleDelete();

break;

default:

cerr << “Unrecognized message received: “ << inMessage << endl; break;

}

}

777

Chapter 26

When the event-handling portion of the program or framework receives a message, it finds the corresponding shape and calls handleMessage(). Through polymorphism, the subclass’s version of handleMessage() is called. This gives the leaf node first crack at handling the message. If it doesn’t know how to handle it, it passes it up to its superclass, which gets the next chance. In this example, the final recipient of the message simply prints an error if it is unable to handle the event. You could also throw an exception or have your handleMessage() method return a boolean indicating success or failure.

Note that while event chains usually correlate with the class hierarchy, they do not have to. In the preceding example, the Square class could have just as easily passed the message to an entirely different object. The chained approach is flexible and has a very appealing structure for object-oriented hierarchies. The downside is that it requires diligence on the part of the programmer. If you forget to chain up to the superclass from a subclass, events will effectively get lost. Worse, if you chain to the wrong class, you could end up in an infinite loop!

Using a Chain of Responsibility

For a chain of responsibility to respond to events, there must be another class that dispatches the events to the correct object. Because this task varies so greatly by framework or platform, pseudocode for handling a mouse down event is presented below in lieu of platform-specific C++ code.

MouseLocation loc = getClickLocation();

Shape* clickedShape = findShapeAtLocation(loc);

clickedShape->handleMessage(kMessageMouseDown);

The Obser ver Pattern

The other common model for event handling is known as observer, listener messaging, or publish and subscribe. This is a more prescriptive model that is often less error-prone than message chains. With the publish and subscribe technique, individual objects register the events they are able to understand with a central event handling registry. When an event is received, it is transmitted to the list of subscribed objects.

Example: Event Handling

Just as with the earlier chain of responsibility pattern, observers are often used to handle events. The main difference between the two patterns is that the chain of responsibility works best for logical hierarchies where you need to find the correct class to handle the event. Observers work best when events can be handled by multiple objects or are unrelated to a hierarchy.

Implementation of an Observer

The definition of a simple event registry class is shown in the following example. It allows any object that extends the mix-in class Listener to subscribe to one or more events. It also contains a method for

778

Applying Design Patterns

the program to call when an event is received, which will dispense the event to all subscribed

Listeners.

/**

*Listener.h

*Mix-in class for objects that are able to respond to events

*/

class Listener

{

public:

virtual void handleMessage(int inMessage) const = 0;

};

/**

*EventRegistry.h

*Maintains a directory of Listeners and their corresponding events. Also

*handles transmission of an event to the appropriate Listener.

*/

#include “Listener.h” #include <vector> #include <map>

class EventRegistry

{

public:

static void registerListener(int inMessage, const Listener* inListener);

static void handleMessage(int inMessage);

protected:

static std::map<int, std::vector<const Listener*> > sListenerMap;

};

The implementation of the EventRegistry class follows. When a new Listener is registered, it is added to the vector of Listener references stored in the listener map for the given event. When an event is received, the registry simply retrieves the vector and passes the event to each Listener.

/**

*EventRegistry.cpp

*Implements the EventRegistry class

*/

#include “EventRegistry.h” #include <iostream>

using namespace std;

779