出错代码:
#ifndef _OBSERVER
#define _OBSERVER
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
class Observer {
public:
virtual ~Observer() {}
virtual void notify() = 0;
};
class ObserverA : public Observer {
public:
void notify() {
cout << "ObserverA is notified that Subject change." << endl;
}
};
class ObserverB : public Observer {
public:
void notify() {
cout << "ObserverB is notified that Subject change." << endl;
}
};
class Subject {
public:
void registerObserver(Observer* ob) {
obCo.push_back(*ob); //instantiated from here 不能将容器类型定义为类,而应定义为类的指针,原因不明
}
void unregisterObserver(Observer* ob) {
vector<Observer>::iterator it;
for (it = obCo.begin(); it != obCo.end(); it++)
if (*it == ob)
obCo.erase(it); //这里应该跳出循环
}
void notifyObservers() {
vector<Observer>::iterator it;
for (it = obCo.begin(); it != obCo.end(); it++)
(*it).notify();
}
private:
vector<Observer> obCo; //类型定义为Observer*
} //类的分号啊!!!不要再忘了
#endif
标程:
#ifndef Observer_Observer_h
#define Observer_Observer_h
#include <iostream>
#include <vector>
using namespace std;
class Observer {
public:
virtual ~Observer() {
}
virtual void notify() = 0;
};
class ObserverA : public Observer {
public:
virtual void notify() {
cout << "ObserverA is notified that Subject change." << endl;
}
virtual ~ObserverA() {
}
};
class ObserverB : public Observer {
public:
virtual void notify() {
cout << "ObserverB is notified that Subject change." << endl;
}
virtual ~ObserverB() {
}
};
class Subject {
private:
vector<Observer*> observers;
public:
Subject() {
}
void registerObserver(Observer* observer) {
observers.push_back(observer);
}
void unregisterObserver(Observer* observer) {
vector<Observer*>::iterator itr = observers.begin();
while (itr != observers.end()) {
if (*itr == observer) {
observers.erase(itr);
break;
}
itr++;
}
}
void notifyObserver() {
for (int i = 0; i < observers.size(); i++)
observers[i] -> notify();
}
};
#endif