题目,
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();
}
};
网友评论