这是我目前正在排除故障的代码:
void CTimer::notify()
{
std::vector<IObserver*>::iterator it;
for(it=observers.begin();it!=observers.end();++it)
{
ITimerNotification* notification = new CTimerNotification(now());
(*it)->readNotification(*notification);
}
}
class CTimerNotification : public ITimerNotification
{
public:
CTimerNotification(const timeval& t)
{
time = t;
}
protected:
timeval time;
private:
virtual ~CTimerNotification();
virtual void read(const IObserver& o) const
{
o.update(*this);
}
virtual const timeval& getTime() const
{
return time;
}
};
class IObserver
{
public:
virtual ~IObserver();
virtual void readNotification(const INotification&) const=0;
virtual void update(const INotification&) const=0;
};
class ITimerObserver : public IObserver
{
public:
virtual void update(const ITimerNotification&) const=0;
};
class TestObserver : public ITimerObserver
{
public:
virtual void readNotification(const INotification& n) const
{
n.read(*this);
}
virtual void update(const INotification& n) const
{
std::cout<<"???: TestObserver: update()!\n";
}
virtual void update(const ITimerNotification& n) const
{
std::cout<< n.getTime().tv_sec << "." << n.getTime().tv_usec <<": TestObserver: update()!\n";
}
};
所以代码运行,CTimer::notify()
被调用,它创建 aTimerNotification
并将其传递给观察者,观察者readNotification()
又通过它调用通知的read()
方法,最后调用观察者的(希望)正确的update()
方法。
最后一步是失败的。它调用update(INotification&)
方法而不是所需的update(ITimerNotification&)
方法。
为了使这种尝试的双重调度模式起作用,我在这里缺少什么?它似乎没有获得正确的类型信息来选择适当的函数调用。
谢谢你的帮助!