Structural Pattern Distinctions and Behavioral Patterns: Chain of Responsibility & Command

This section covers two major topics from the Gang of Four: first, the nuanced distinctions between structurally similar patterns (Adapter vs Bridge, Composite vs Decorator vs Proxy), and second, the introduction to Behavioral Patterns with full coverage of Chain of Responsibility and the beginning of Command. The structural comparisons clarify when superficially similar patterns serve fundamentally different intents. The behavioral patterns shift focus from object composition to algorithms, responsibilities, and communication between objects.

Key Concepts

Structural Pattern Distinctions:

Behavioral Patterns Overview:

Chain of Responsibility:

Command:

Commands and Syntax

Chain of Responsibility — Handler base class:


class HelpHandler {
public:
    HelpHandler(HelpHandler* s) : _successor(s) { }
    virtual void HandleHelp();
private:
    HelpHandler* _successor;
};

void HelpHandler::HandleHelp() {
    if (_successor) {
        _successor->HandleHelp();
    }
}

Chain of Responsibility — Widget hierarchy with help:


class Widget : public HelpHandler {
protected:
    Widget(Widget* parent, Topic t = NO_HELP_TOPIC);
private:
    Widget* _parent;
};

class Button : public Widget {
public:
    Button(Widget* d, Topic t = NO_HELP_TOPIC);
    virtual void HandleHelp();
};

void Button::HandleHelp() {
    if (HasHelp()) {
        // offer help on the button
    } else {
        HelpHandler::HandleHelp();  // forward to successor
    }
}

Request dispatch with request objects:


void Handler::HandleRequest(Request* theRequest) {
    switch (theRequest->GetKind()) {
        case Help:
            HandleHelp((HelpRequest*) theRequest);
            break;
        case Print:
            HandlePrint((PrintRequest*) theRequest);
            break;
        default:
            break;
    }
}

Chain setup and invocation:


Application* application = new Application(APPLICATION_TOPIC);
Dialog* dialog = new Dialog(application, PRINT_TOPIC);
Button* button = new Button(dialog, PAPER_ORIENTATION_TOPIC);
button->HandleHelp();  // starts chain traversal

Relationships

Exam-Relevant Points