• 设计模式复习-观察者模式


    #pragma once
    #include "stdafx.h"
    #include<set>
    #include<list>
    #include<string>
    #include<iostream>
    #include<windows.h>
    using namespace std;
    
    //设计模式-观察者模式Observer
    //定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象
    //这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己。
    
    
    class CObserver {//抽象接口
    public:
    	virtual void Update() = 0;
    };
    
    class CSubject {//抽象通知者
    private:
    	set<CObserver *> m_HashMemory;
    public:
    	CSubject(){
    		m_HashMemory.clear();
    	}
    
    	~CSubject() {
    		for each(CObserver *i in m_HashMemory) {
    			delete i;
    		}
    	}
    	void Attach(CObserver *pObserver) {
    		m_HashMemory.insert(pObserver);
    	}
    	void Detach(CObserver *pObserver) {
    		m_HashMemory.erase(pObserver);
    		delete pObserver;
    	}
    	void Notify() {
    		for each(CObserver *i in m_HashMemory) {
    			i->Update();
    		}
    	}
    };
    
    
    class CConcreteSubjuct :public CSubject {//具体的通知着
    private:
    	string m_strSubjectState;
    public:
    	CConcreteSubjuct(const string &strName) {
    		m_strSubjectState = strName;
    	}
    	string GetName() {
    		return m_strSubjectState;
    	}
    };
    
    
    class ConcreteObserver :public CObserver{//具体的观察者
    private:
    	string m_strName;
    	string m_strObserverState;
    	CConcreteSubjuct *m_pSubject;
    public:
    	ConcreteObserver(CConcreteSubjuct *pSubject ,const string &strName) {
    		m_pSubject = pSubject;
    		m_strName = strName;
    	}
    	void Update() {
    		m_strObserverState = m_pSubject->GetName();
    		cout << "观察者" << m_strName << "的新状态是" << m_strObserverState << endl;
    	}
    };
    
    
    int main()
    {
    	
    	//一个前台,几个员工
    	CConcreteSubjuct *pQianTai = new CConcreteSubjuct("QianTai");
    	ConcreteObserver *pYuanGongA = new ConcreteObserver(pQianTai ,"YuanGongA");
    	ConcreteObserver *pYuanGongB = new ConcreteObserver(pQianTai, "YuanGongB");
    	ConcreteObserver *pYuanGongC = new ConcreteObserver(pQianTai, "YuanGongC");
    	pQianTai->Attach(pYuanGongA); pQianTai->Attach(pYuanGongB); pQianTai->Attach(pYuanGongC);
    
    	pQianTai->Notify();
    
    	pQianTai->Detach(pYuanGongB);
    
    	pQianTai->Notify();
    	getchar();
    	return 0;
    }
    

     

  • 相关阅读:
    Java中的面向对象以及java的基本特性
    Redis数据结构(三):双向链表和压缩链表
    java对象晋升的四种情况
    Redis数据结构(一):对外数据类型和底层数据结构
    InnoDB中的的聚合函数count(?)哪个效率高?
    群智能算法标准测试函数集
    运行vue项目时报错“ValidationError: Progress Plugin Invalid Options”
    uswipeaction 宽度计算的延迟导致组件加载时内部样式错误
    地址智能识别相关插件
    js滑动验证
  • 原文地址:https://www.cnblogs.com/csnd/p/12061916.html
Copyright © 2020-2023  润新知