-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20.mediator_pattern.h
102 lines (92 loc) · 2.74 KB
/
20.mediator_pattern.h
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//
// Created by Tianyi Zhang on 4/16/21.
//
#ifndef DESIGN_PATTERN_20_MEDIATOR_PATTERN_H
#define DESIGN_PATTERN_20_MEDIATOR_PATTERN_H
#include <memory>
#include <iostream>
struct Mediator;
struct Colleague : std::enable_shared_from_this<Colleague>{
Colleague(std::shared_ptr<Mediator> mediator):mediator_(mediator){};
protected:
void notifyChange();
private:
std::shared_ptr<Mediator> mediator_;
};
struct Mediator : std::enable_shared_from_this<Mediator>{
virtual void ColleagueChanged(std::shared_ptr<Colleague> changedColleague) = 0;
virtual ~Mediator(){};
};
void Colleague::notifyChange(){
mediator_->ColleagueChanged(shared_from_this());
}
enum Color{
White, Black
};
std::string toString(Color color){
if(color == Color::White)
return "White";
else
return "Black";
}
struct BackGround : public Colleague{
BackGround(std::shared_ptr<Mediator> mediator) : Colleague(mediator){
color_ = Color::White;
}
void setBackGroundColor(Color color){
if(color != color_) {
color_ = color;
std::cout<<"background color set to "<< toString(color)<<std::endl;
notifyChange();
}
}
Color getBackGroundColor(){
return color_;
}
private:
Color color_;
//...other attributes
};
struct Font : public Colleague{
Font(std::shared_ptr<Mediator> mediator) : Colleague(mediator){
color_ = Color::Black;
}
void setFontColor(Color color){
if(color != color_) {
color_ = color;
std::cout<<"font color set to "<< toString(color)<<std::endl;
notifyChange();
}
}
Color getFontColor(){
return color_;
}
private:
Color color_;
//...other attributes
};
struct DisplayMediator : public Mediator{
DisplayMediator() = default;
DisplayMediator& withColleague(std::shared_ptr<BackGround> background, std::shared_ptr<Font> font){
background_ = background;
font_ = font;
return *this;
}
void ColleagueChanged(std::shared_ptr<Colleague> changedColleague) override{
if(changedColleague == background_){
if(background_->getBackGroundColor() == Color::White)
font_->setFontColor(Color::Black);
else if(background_->getBackGroundColor() == Color::Black)
font_->setFontColor(Color::White);
}else if(changedColleague == font_){
if(font_->getFontColor() == Color::White)
background_->setBackGroundColor(Color::Black);
else
background_->setBackGroundColor(Color::White);
}
}
private:
std::shared_ptr<BackGround> background_;
std::shared_ptr<Font> font_;
};
#endif //DESIGN_PATTERN_20_MEDIATOR_PATTERN_H