观察者模式 C++实现

2019-03-13  本文已影响0人  假程序员
//
//  main.cpp
//  observer_pattern
//
//  Created by apple on 2019/3/13.
//  Copyright © 2019年 apple. All rights reserved.
//

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

class IObserver
{
public:
    virtual ~IObserver() {}
    int num;
    IObserver(string name){this->num = 0;this->name = name;}
    string name;
    virtual void up() = 0;
};
class Observer:public IObserver
{
public:
    Observer(string name):IObserver(name){}
    void up(){this->num++;}
};
class ISubject
{
public:
    list<IObserver *> observers;
    virtual void register_observer(IObserver *) = 0;
    virtual void remove_observer(IObserver *) = 0;
    virtual void clear_observer() = 0;
    virtual void test() = 0;
    virtual ~ISubject()
    {
        while (!observers.empty()) {
            cout<<"delete "<<observers.front()->name<<endl;
            IObserver *temp = observers.front();
            observers.pop_front();
            delete temp;
        }
    }
};
class Subject:public ISubject
{
public:
    void register_observer(IObserver *observer){this->observers.push_back(observer);}
    void remove_observer(IObserver *observer){this->observers.remove(observer);}
    void clear_observer(){this->observers.clear();}
    void test()
    {
        list<IObserver *>::iterator temp;
        for (temp = this->observers.begin() ; temp != observers.end(); ++temp) {
            (*temp)->up();
            cout<<(*temp)->name<<":"<<(*temp)->num<<endl;
        }
    }
};

int main(int argc, const char * argv[]) {
    Subject subject;
    IObserver *observer = new Observer("A");
    subject.register_observer(observer);
    observer->up();
    subject.register_observer(new Observer("B"));
    subject.register_observer(new Observer("C"));
    subject.test();
    return 0;
}
A:2
B:1
C:1
delete A
delete B
delete C
Program ended with exit code: 0
上一篇下一篇

猜你喜欢

热点阅读