美文网首页
C++11观察者模式

C++11观察者模式

作者: FredricZhu | 来源:发表于2021-07-16 11:36 被阅读0次

题目,


image.png

构造函数时subscribe,并notify
析构函数时unsubscribe,并notify。
纯粹的观察者模式。

代码如下,

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct IRat {
    int attack{1};
};

struct Game
{
    vector<IRat*> rats;
    
    void notify() {
        for(auto&& rat: rats)  {
            rat->attack = rats.size();
        }
    }
    
    void subscribe(IRat* rat) {
        rats.push_back(rat);
    }
    
    void unsubscribe(IRat* rat) {
        auto result = find(begin(rats), end(rats), rat);
        rats.erase(result);
    }
};

struct Rat : IRat
{
    Game& game;
    
    Rat(Game &game) : game(game)
    {
        game.subscribe(this);
        game.notify();
    }

    ~Rat() 
    { 
        game.unsubscribe(this);
        game.notify();
    }
};

相关文章

  • C++11观察者模式

    题目, 构造函数时subscribe,并notify析构函数时unsubscribe,并notify。纯粹的观察者...

  • 11.9设计模式-观察者模式-详解

    设计模式-观察者模式 观察者模式详解 观察者模式在android中的实际运用 1.观察者模式详解 2.观察者模式在...

  • RxJava基础—观察者模式

    设计模式-观察者模式 观察者模式:观察者模式(有时又被称为发布(publish )-订阅(Subscribe)模式...

  • 前端面试考点之手写系列

    1、观察者模式 观察者模式(基于发布订阅模式) 有观察者,也有被观察者。 观察者需要放到被观察者列表中,被观察者的...

  • RxJava 原理篇

    一、框架思想 观察者模式观察者自下而上注入被观察者被观察者自上而下发射事件观察者模式 装饰器模式自上而下,被观察者...

  • 观察者模式

    观察者模式概念 观察者模式是对象的行为模式,又叫作发布-订阅(publish/subscrible)模式。 观察者...

  • 设计模式-观察者模式

    观察者模式介绍 观察者模式定义 观察者模式(又被称为发布-订阅(Publish/Subscribe)模式,属于行为...

  • 观察者模式

    观察者模式 观察者模式的定义 观察者模式(Observer Pattern)也叫做发布订阅模式(Publish/s...

  • iOS设计模式之观察者模式

    观察者模式 1、什么是观察者模式 观察者模式有时又被称为发布(publish)-订阅(Subscribe)模式、模...

  • 观察者模式和发布订阅模式区别

    观察者模式 所谓观察者模式,其实就是为了实现松耦合(loosely coupled)。 在观察者模式中,观察者需要...

网友评论

      本文标题:C++11观察者模式

      本文链接:https://www.haomeiwen.com/subject/pczvpltx.html