好奇的探索者,理性的思考者,踏实的行动者。
观察者模式
#include <algorithm>
#include <vector>
#include <stdio.h>
class Observable;
class Observer
{public:
virtual ~Observer();
virtual void update() = 0;
void observe(Observable* s);
protected:
subject_;
Observable*
};
class Observable
{public:
void register_(Observer* x);
void unregister(Observer* x);
void notifyObservers()
{for (size_t i = 0; i < observers_.size(); ++i)
{observers_[i];
Observer* x = if (x) {
// (3)
x->update();
}
}
}
private:
std::vector<Observer*> observers_;
};
Observer::~Observer()
{subject_->unregister(this);
}
void Observer::observe(Observable* s)
{register_(this);
s->subject_ = s;
}
void Observable::register_(Observer* x)
{observers_.push_back(x);
}
void Observable::unregister(Observer* x)
{std::vector<Observer*>::iterator it = std::find(observers_.begin(), observers_.end(), x);
if (it != observers_.end())
{std::swap(*it, observers_.back());
observers_.pop_back();
}
}
// ---------------------
class Foo : public Observer
{virtual void update()
{"Foo::update() %p\n", this);
printf(
}
};
int main()
{new Foo;
Foo* p =
Observable subject;
p->observe(&subject);
subject.notifyObservers();delete p;
subject.notifyObservers(); }