#ifndef Observer_hpp
#define Observer_hpp
#define CC_SYNTHESIZE(varType, varName, funName)\
protected: varType varName;\
public: virtual varType get##funName(void) const { return varName; }\
public: virtual void set##funName(varType var){ varName = var; }
#include <stdio.h>
#include <iostream>
using namespace std;
class Observer {
public:
Observer() {};
~Observer() {};
virtual void update();
virtual void showSelf();
CC_SYNTHESIZE(string,name,Name);
};
#endif /* Observer_hpp */
#include "Observer.hpp"
void Observer::update() {
printf("我观察到啦!%s\n" , this->getName().c_str());
this->showSelf(); //看看是否能调用到子类
}
void Observer::showSelf() {
printf("展示自己Observer\n");
}
#ifndef Observerable_hpp
#define Observerable_hpp
#include <stdio.h>
#include <iostream>
#include "list"
#include "Observer.hpp"
using namespace std;
class Observerable {
public:
Observerable() {};
~Observerable() {};
virtual void addObserver(Observer *observer);
virtual void removeObserver(Observer *observer);
virtual void clearObserver();
virtual void postNotify();
list<Observer *> mylist;
};
#endif /* Observerable_hpp */
#include "Observerable.hpp"
void Observerable::addObserver(Observer *observer) {
mylist.push_back(observer);
}
void Observerable::removeObserver(Observer *observer) {
mylist.remove(observer);
}
void Observerable::clearObserver() {
mylist.clear();
}
void Observerable::postNotify() {
list<Observer *>::iterator itr;
for (itr = mylist.begin(); itr != mylist.end(); itr ++) {
(*itr)->update();
}
}
#ifndef StarZhou_hpp
#define StarZhou_hpp
#include <stdio.h>
#include "Observerable.hpp"
class StarZhou: public Observerable {
public:
StarZhou();
~StarZhou();
void haveBreakFast();
void haveFun();
};
#endif /* StarZhou_hpp */
#include "StarZhou.hpp"
StarZhou::StarZhou () {
}
StarZhou::~StarZhou () {
}
void StarZhou::haveBreakFast() {
printf("我在吃饭\n");
this->postNotify();
}
void StarZhou::haveFun() {
printf("我在玩\n");
this->postNotify();
}
#ifndef Gouzai_hpp
#define Gouzai_hpp
#include <stdio.h>
#include "Observer.hpp"
class Gouzai :public Observer {
public:
Gouzai();
~Gouzai();
void showSelf();
};
#endif /* Gouzai_hpp */
#include "Gouzai.hpp"
Gouzai::Gouzai() {
}
Gouzai::~Gouzai() {
}
void Gouzai::showSelf() {
printf("展示自己Gouzai+ %s\n",this->getName().c_str());
}
/*
观察者模式
*/
#include <iostream>
#include "StarZhou.hpp"
#include "Gouzai.hpp"
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, 观察者!\n";
StarZhou* zhou = new StarZhou();
Gouzai* gouzai = new Gouzai();
gouzai->setName("偷拍达人1");
Gouzai* gouzai2 = new Gouzai();
gouzai2->setName("偷拍达人2");
Gouzai* gouzai3 = new Gouzai();
gouzai3->setName("偷拍达人3");
Gouzai* gouzai4 = new Gouzai();
gouzai4->setName("偷拍达人4");
zhou->addObserver(gouzai);
zhou->addObserver(gouzai2);
zhou->addObserver(gouzai3);
zhou->addObserver(gouzai4);
zhou->haveBreakFast();
return 0;
}
c++ 观察者模式
最新推荐文章于 2024-09-27 19:35:53 发布