-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver_coding_exercise_17.cpp
More file actions
62 lines (54 loc) · 1.17 KB
/
Copy pathobserver_coding_exercise_17.cpp
File metadata and controls
62 lines (54 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct IRat
{
virtual void rat_enters(IRat* sender) = 0;
virtual void rat_dies(IRat* sender) = 0;
virtual void notify(IRat* target) = 0;
};
struct Game
{
vector<IRat*> rats;
virtual void fire_rat_enters(IRat* sender)
{
for (auto rat : rats) rat->rat_enters(sender);
}
virtual void fire_rat_dies(IRat* sender)
{
for (auto rat : rats) rat->rat_dies(sender);
}
virtual void fire_notify(IRat* target)
{
for (auto rat : rats) rat->notify(target);
}
};
struct Rat : IRat
{
Game& game;
int attack{1};
Rat(Game &game) : game(game)
{
game.rats.push_back(this);
game.fire_rat_enters(this);
}
~Rat()
{
game.fire_rat_dies(this);
game.rats.erase(std::remove(game.rats.begin(),game.rats.end(),this));
}
void rat_enters(IRat *sender) override {
if (sender != this)
{
++attack;
game.fire_notify(sender);
}
}
void rat_dies(IRat *sender) override {
--attack;
}
void notify(IRat *target) override {
if (target == this) ++attack;
}
};