Command Pattern: Undo/Redo, Logging, and Transactions + Interpreter Pattern

This document covers the second half of the Command pattern (implementation details, undo/redo mechanics, sample code) and the complete Interpreter pattern from the Gang of Four. Command focuses on encapsulating requests as objects to support undo, logging, and macro composition. Interpreter focuses on representing a grammar as a class hierarchy and evaluating sentences in that grammar via recursive interpretation.

Key Concepts

Command Pattern (continued):

Interpreter Pattern:

Commands and Syntax

Command Pattern — MacroCommand (C++):


class MacroCommand : public Command {
public:
    virtual void Execute();
    virtual void Add(Command*);
    virtual void Remove(Command*);
private:
    List<Command*>* _cmds;
};

void MacroCommand::Execute() {
    ListIterator<Command*> i(_cmds);
    for (i.First(); !i.IsDone(); i.Next()) {
        Command* c = i.CurrentItem();
        c->Execute();
    }
}
// Unexecute must reverse the order

SimpleCommand template (C++):


template <class Receiver>
class SimpleCommand : public Command {
    typedef void (Receiver::* Action)();
    SimpleCommand(Receiver* r, Action a);
    virtual void Execute() { (_receiver->*_action)(); }
};

// Usage:
Command* cmd = new SimpleCommand<MyClass>(receiver, &MyClass::Action);

Interpreter Pattern — Regular Expression Grammar:


expression ::= literal | alternation | sequence | repetition | '(' expression ')'
alternation ::= expression '|' expression
sequence    ::= expression '&' expression
repetition  ::= expression '*'
literal     ::= 'a' | 'b' | 'c' | ...

Interpreter Pattern — Boolean Expression Grammar (C++):


BooleanExp  ::= VariableExp | Constant | OrExp | AndExp | NotExp
AndExp      ::= BooleanExp 'and' BooleanExp
OrExp       ::= BooleanExp 'or' BooleanExp
NotExp      ::= 'not' BooleanExp

Smalltalk AST construction via operator overloading:


('dog' | 'cat') repeat & 'weather'
"Builds AST: SequenceExpression(RepetitionExpression(AlternationExpression(...)), ...)"

Relationships

Command pattern connections:

Interpreter pattern connections:

Exam-Relevant Points