-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLinary_Decorator.h
88 lines (76 loc) · 1.6 KB
/
Linary_Decorator.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
/*****************************************************************/
/* 设计模式————装饰模式
/* 作者:李凝瑞
/* 时间:2015.04.01
/*****************************************************************/
#pragma once
namespace linary_decorator {
// 抽象电话类,类比于抽象组件类
class Phone {
public:
// 开启应用的方法
virtual void Run() = 0;
};
// 具体电话类
class IPhone : public Phone {
public:
virtual void Run() {
std::cout << "欢迎使用IPhone" << std::endl;
}
};
// 抽象应用类,类比于抽象装饰者类
class App : public Phone {
public:
// 表示把App安装在手机上
void InstallOn(Phone * phone) {
this->phone = phone;
}
virtual void Run() {
if (phone != NULL) {
phone->Run();
}
}
protected:
Phone * phone;
};
// 具体应用类
class Douban : public App {
public:
virtual void Run() {
App::Run();
SearchMovie();
}
private:
void SearchMovie() {
std::cout << "您可以使用豆瓣搜索电影" << std::endl;
}
};
// 具体应用类
class Wechat : public App {
public:
virtual void Run() {
App::Run();
Chat();
}
private:
void Chat() {
std::cout << "您可以使用微信聊天" << std::endl;
}
};
// 测试代码
static void Test_Decorator() {
std::cout << "--------------------------" << std::endl;
std::cout << "-- 装饰模式测试 --" << std::endl;
std::cout << "--------------------------" << std::endl;
IPhone * iphone = new IPhone();
Douban * douban = new Douban();
Wechat * wechat = new Wechat();
douban->InstallOn(iphone);
wechat->InstallOn(douban);
wechat->Run();
delete wechat;
delete douban;
delete iphone;
std::cout << std::endl;
}
}