设计模式---观察者模式(C++实现)

来源:互联网 发布:王者荣耀网络不稳定 编辑:程序博客网 时间:2024/05/17 23:33

#include "stdafx.h"
#include <iostream>
#include <list>
#include <numeric>
#include <algorithm>
using namespace std;
//
//
//  Generated by StarUML(tm) C++ Add-In
//
//  @ Project : Untitled
//  @ File Name : INotifier.h
//  @ Date : 2016-11-8
//  @ Author : richard.liu
//
//

class TecherListenner {
public:
virtual void onTecherComming() = 0;
};

class INotifier {
public:
virtual void addListenner(TecherListenner* listenner) = 0;
virtual void removeListenner(TecherListenner* removeListenner) = 0;
virtual void notify() = 0;
};

class TecherNotifier : public INotifier {
public:
list<TecherListenner*> m_listenners;
void addListenner(TecherListenner* listenner);
void removeListenner(TecherListenner* listenner);
void notify();
};

void TecherNotifier::addListenner(TecherListenner* listenner) {
m_listenners.push_back(listenner);  
}

void TecherNotifier::removeListenner(TecherListenner* listenner) {
m_listenners.push_back(listenner);  
}

void TecherNotifier::notify() {
list <TecherListenner*> ::iterator it = m_listenners.begin();  
        for (; it != m_listenners.end(); ++ it)  
        {  
            (*it)->onTecherComming();
        }  
}


class XiaoZhang : public TecherListenner {
public:
void onTecherComming();
void stopCopyWork();
void copyHomeWork();
};

void XiaoZhang::onTecherComming() {
stopCopyWork();
}

void XiaoZhang::stopCopyWork() {
cout << "stop copy homework" << endl;
}

void XiaoZhang::copyHomeWork() {
cout << "copy homework now" << endl;
}

int main(int argc, char* argv[])
{
TecherNotifier monitor;  
XiaoZhang xz;  
monitor.addListenner(&xz);  
xz.copyHomeWork();  
monitor.notify();  
printf("Hello World!\n");
return 0;
}

0 0
原创粉丝点击