Observer pattern

观察者模式,详情请看: http://en.wikipedia.org/wiki/Observer_pattern
main.cpp:
#include "observer_pattern.h"

student s[5];
teacher t[5];

void tell_us_what_you_know() {
    for (int i = 0; i < 5; i++) {
        cout << "Student_" << i << " knows " << s[i].what_i_know() << endl;
    }
    for (int i = 0; i < 5; i++) {
        cout << "Teacher_" << i << " knows " << t[i].what_i_know() << endl;
    }
    cout << endl;
}

int main() {

    subject TeachingAffairsOffice;
    for (int i = 0; i < 5; i++) {
        TeachingAffairsOffice.registerObserver(s + i);
        TeachingAffairsOffice.registerObserver(t + i);
    }
    TeachingAffairsOffice.notifyObserver("the students of Grade 13 are all given an F in mid-term examination.");
    tell_us_what_you_know();
    TeachingAffairsOffice.notifyObserver("it's just a joke.");
    tell_us_what_you_know();
    TeachingAffairsOffice.notifyObserver("it's a real joke");
    tell_us_what_you_know();
}
observer_pattern.h:
#ifndef __OBSERVER_PATTERN_H
#define __OBSERVER_PATTERN_H

#include <iostream>
#include <string>
#include <list>
using namespace std;

class observer {
  public:
    observer() {
        message = "nothing";
    }
    void notify(string new_message) {
        message = new_message;
    }
    string what_i_know() {
        return message;
    }
  private:
    string message;
};

class student: public observer {};

class teacher: public observer {};

class subject {
  public:
    void registerObserver(observer* new_observer) {
        for (iter = l.begin(); iter != l.end(); iter++) {
            if (*iter == new_observer) {
                cout << "The observer you want to register already exists!" << endl;
                return;
            }
        }
        l.push_back(new_observer);
    }
    void unregisterObserver(observer* the_observer) {
        for (iter = l.begin(); iter != l.end(); iter++) {
            if (*iter == the_observer) {
                l.erase(iter);
                return;
            }
        }
        cout << "The observer you want to unregister does not exists!" << endl;
    }
    void notifyObserver(string message) {
        for (iter = l.begin(); iter != l.end(); iter++) {
            (*iter)->notify(message);
        }
    }
  private:
    list<observer*> l;
    list<observer*>::iterator iter;
};

#endif



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值