Memento for Iteration, Observer Pattern, and State Pattern (GoF Behavioral Patterns)

This excerpt covers three behavioral design patterns from the Gang of Four: the conclusion of the Memento pattern (focusing on its use for iteration), the complete Observer pattern, and the beginning of the State pattern. Together they address how objects manage state snapshots, propagate change notifications, and vary behavior based on internal state.

Key Concepts

Commands and Syntax

Memento-based iteration (C++):


Collection<ItemType*> aCollection;
IterationState* state;
state = aCollection.CreateInitialState();
while (!aCollection.IsDone(state)) {
    aCollection.CurrentItem(state)->Process();
    aCollection.Next(state);
}
delete state;

Observer abstract classes:


class Observer {
public:
    virtual ~Observer();
    virtual void Update(Subject* theChangedSubject) = 0;
protected:
    Observer();
};

class Subject {
public:
    virtual void Attach(Observer*);
    virtual void Detach(Observer*);
    virtual void Notify();
private:
    List<Observer*> *_observers;
};

void Subject::Notify() {
    ListIterator<Observer*> i(_observers);
    for (i.First(); !i.IsDone(); i.Next()) {
        i.CurrentItem()->Update(this);
    }
}

Observer registration with aspects (selective notification):


void Subject::Attach(Observer*, Aspect& interest);
void Observer::Update(Subject*, Aspect& interest);

Template Method to ensure consistent state before notification:


void Text::Cut(TextRange r) {
    ReplaceRange(r);  // redefined in subclasses
    Notify();         // always last — state is consistent
}

State pattern — Context delegates to state object:


TCPConnection -> TCPState (abstract)
                   |-> TCPEstablished
                   |-> TCPListen
                   |-> TCPClosed

Relationships

Exam-Relevant Points