我指的是Implementing a Subject/Observer pattern with templates
我做了一些修改,结果变成如下代码。
template <class T, class A>
class Observer {
public:
Observer() {}
virtual ~Observer() {}
virtual void update(T& subject, A arg) = 0;
};
template <class T, class A>
class Subject
{
public:
Subject() {}
virtual ~Subject() {}
// Take note that, we didn't make the following functions as virtual,
// as we do not expect them to be overridden.
void attach(Observer<T, A> &observer) {
// Ensure no duplication.
std::vector<Observer<T, A> *>::const_iterator iterator = std::find(observers.begin(), observers.end(), &observer);
if (iterator == observers.end()) {
observers.push_back(&observer);
}
}
void dettach(Observer<T, A> &observer) {
std::vector<Observer<T, A> *>::const_iterator iterator = std::find(observers.begin(), observers.end(), &observer);
if (iterator != observers.end()) {
observers.erase(iterator);
}
}
void dettachAll() {
observers.clear();
}
void notify(A arg)
{
std::vector<Observer<T, A> *>::const_iterator it;
for (it = observers.begin(); it != observers.end(); it++) {
(*it)->update(*(static_cast<T *>(this)), arg);
}
}
private:
std::vector<Observer<T, A> *> observers;
};
后来,我意识到
(*it)->update(*(static_cast<T *>(this)), arg);
有局限性。例如,// cause compilation error in static_cast, as it cannot cast cat1 to animal.
class cat1 : public animal, public Subject<animal, int> {
public:
virtual void speak() {
notify(888);
}
};
class zoo1 : public Observer<animal, int> {
public:
zoo1() {
c.attach(*this);
c.speak();
}
virtual void update(animal& subject, int arg) {
cout << "zoo1 received notification " << arg << endl;
}
cat1 c;
};
我可以通过将
static_cast
更改为dynamic_cast
来解决问题。 但是,我不确定是否会陷入其他陷阱? 我对作者拥有static_cast
的初衷是为了确保在编译期间进行类型安全检查。 最佳答案
您的问题来自这样一个事实,即动物不仅应该是猫的主体,
class animal : public Subject<animal,int>
{
...
};
class cat1 : public animal
{
public:
virtual void speak()
{
notify(888);
}
};
class zoo1 : public Observer<animal, int> {
public:
zoo1()
{
c.attach(*this);
c.speak();
}
virtual void update(animal& subject, int arg)
{
cout << "zoo1 received notification " << arg << endl;
}
cat1 c;
};
通过这样做,每个对象都可以对动物“静态”投射。您的cat1并非如此