forked from mrn3088/patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMediator.hpp
More file actions
72 lines (68 loc) · 1.93 KB
/
Mediator.hpp
File metadata and controls
72 lines (68 loc) · 1.93 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
63
64
65
66
67
68
69
70
71
72
// warning: this is problematic!
#ifndef Mediator_hpp
#define Mediator_hpp
#include <string>
#include <memory>
#include <vector>
#include <iostream>
class Mediator;
class Component
{
public:
Component(std::shared_ptr<Mediator> aMediator) : m_mediator(aMediator) {}
virtual void sendMessage(const std::string &aString) = 0;
virtual void receiveMessage(const std::string &aString) = 0;
protected:
std::shared_ptr<Mediator> m_mediator;
};
class Mediator
{
public:
Mediator() = default;
Mediator ®isterComponent(std::shared_ptr<Component> theComponent)
{
m_components.push_back(theComponent);
return *this;
}
Mediator ¬ify(Component *aSender, const std::string &aMessage)
{
std::for_each(m_components.begin(), m_components.end(),
[&](std::shared_ptr<Component> aComponent)
{
if (aComponent.get() != aSender) {
aComponent ->receiveMessage(aMessage);
} });
return *this;
}
protected:
std::vector<std::shared_ptr<Component>> m_components;
};
class Button : public Component
{
public:
Button(std::shared_ptr<Mediator> aMediator) : Component(aMediator) {}
void sendMessage(const std::string &aString) override
{
std::cout << "Button updated: " << aString << std::endl;
m_mediator->notify(this, aString);
}
void receiveMessage(const std::string &aString) override
{
std::cout << "Button received: " << aString << std::endl;
}
};
class Label : public Component
{
public:
Label(std::shared_ptr<Mediator> aMediator) : Component(aMediator) {}
void sendMessage(const std::string &aString) override
{
std::cout << "Label updated: " << aString << std::endl;
m_mediator->notify(this, aString);
}
void receiveMessage(const std::string &aString) override
{
std::cout << "Label received: " << aString << std::endl;
}
};
#endif