zoukankan      html  css  js  c++  java
  • 设计模式

    在这里插入图片描述

    #include <iostream>
    #include <list>
    #include <string>
    using namespace std;
    class ISubject;
    class IObserver;
    class Subject;
    class Observer;
    
    
    class ISubject {
    private:
    	list<IObserver*> observerList;
    public:
    	void AddObserver(IObserver *obs) {
    		observerList.push_back(obs);
    	};
    	void RemoveObserver(IObserver *obs) {
    		observerList.remove(obs);
    	};
    	virtual void Notified(IObserver *) = 0;
    
    	void Update() {
    		for (auto ob : observerList)
    		{
    			if (ob != NULL) {
    				Notified(ob);
    			}
    		}
    	}
    };
    
    class IObserver {
    public:
    	virtual void Received(ISubject *) = 0;
    };
    
    // 实例:发布者
    class Subject :public ISubject
    {
    public:
    	Subject() :ISubject() {	};
    	void Notified(IObserver *obs) {
    		obs->Received(this);
    	}
    };
    
    // 实例:接收(观察)者
    class Observer :public IObserver
    {
    public:
    	Observer(string& n) {
    		name = n;
    	};
    	void Received(ISubject *sub) {
    		cout << "this is " + name + " OBer, Received.
    ";
    	}
    private:
    	string name;
    };
    
    int main() {
    	string val = "1";
    	Observer *obs1 = new Observer(val);
    	val = "2";
    	Observer *obs2 = new Observer(val);
    	val = "3";
    	Observer *obs3 = new Observer(val);
    
    	Subject *sub = new Subject();
    
    	// 订阅消息
    	sub->AddObserver(obs1);
    	sub->AddObserver(obs2);
    	sub->AddObserver(obs3);
    
    	// 发布消息
    	sub->Update();
    	cout << "///////////////////////////////
    ";
    	sub->RemoveObserver(obs2);
    	sub->Update();
    	cout << "///////////////////////////////
    ";
    
    	/*
    	this is 1 OBer, Received.
    	this is 2 OBer, Received.
    	this is 3 OBer, Received.
    	///////////////////////////////
    	this is 1 OBer, Received.
    	this is 3 OBer, Received.
    	///////////////////////////////
    	*/
    	system("pause");
    	return 0;
    }
    
  • 相关阅读:
    让keep-alive不缓存
    vue tab echart始终显示100px解决办法
    加载图片失败显示默认图片
    element 文件上传传参数
    vue-cli axios 拦截器设置
    制作字体图标制作
    20道Java面试必考题
    Integer源码解析
    阿里P9架构师讲解从单机至亿级流量大型网站系统架构的演进过程
    代理详解
  • 原文地址:https://www.cnblogs.com/ruoh3kou/p/11230572.html
Copyright © 2011-2022 走看看