主题观察者模式动态转换通过参考文章Implementing a Subject/Observer pattern with templates我应该使用与模板
template <class T>
class Observer
{
public:
Observer() {}
virtual ~Observer() {}
virtual void update(T *subject)= 0;
};
template <class T>
class Subject
{
public:
Subject() {}
virtual ~Subject() {}
void attach (Observer<T> &observer)
{
m_observers.push_back(&observer);
}
void notify()
{
std::vector<Observer<T> *>::iterator it;
for (it=m_observers.begin();it!=m_observers.end();it++)
(*it)->update(static_cast<T *>(this));
}
private:
std::vector<Observer<T> *> m_observers;
};
我想知道的,而不是static_cast
,我将使用dynamic_cast
?
这是因为如果我使用static_cast
,在以下情况下会出现编译错误。
class Zoo : public Observer<Animal> {
public:
Zoo() {
animal = new Bird();
animal->attach(this);
}
virtual ~Zoo() {
delete animal;
}
virtual void update(Animal* subject) {
}
Animal* animal;
}
// If using static_cast, compilation error will happen here.
class Bird : public Animal, public Subject<Animal> {
public:
virtual ~Bird() {
}
}
使用dynamic_cast
有什么副作用吗?