我必須創建一個類,它觀察一個矢量,並在每次改變時都會收到通知。我的問題是,我的程序不會改變向量的內容。有人可以告訴我,我犯了一個錯誤嗎?列表觀察者不會「看到」更新
實施:
class IObserver
{
public:
virtual void notify() = 0;
virtual ~IObserver(){};
};
class ObservableVector
{
vector<int> ov;
vector<IObserver*> registered;
public:
void notifyObserver()
{
for (IObserver* el : registered)
{
el->notify();
}
}
void add(int n)
{
ov.push_back(n);
notifyObserver();
}
void registerObserver(IObserver* obs)
{
registered.push_back(obs);
}
const vector<int> & items() const
{
vector<int> it;
for (int el : ov)
{
it.push_back(el);
}
return it;
}
};
class ListingObserver : public IObserver
{
ObservableVector & _ov;
public:
ListingObserver(ObservableVector & ov) : _ov(ov)
{
_ov.registerObserver(this);
}
void notify()
{
vector<int> toNotify;
toNotify = _ov.items();
cout << "Elements: " << endl;
for (int el : toNotify)
{
cout << el << endl;
}
}
};
int main()
{
ObservableVector ov;
ListingObserver lo(ov);
//MeanObserver mo(ov);
ov.add(1);
ov.add(2);
ov.add(3);
}
感謝您的幫助! :)它現在完美:) – LittleBunchie