c++オブザーバモード


#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
" , this->getName().c_str()); this->showSelf(); // } void Observer::showSelf() { printf(" Observer
"); } #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("
"); this->postNotify(); } void StarZhou::haveFun() { printf("
"); 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
",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, !
"; 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; }