2021/11/9
装饰模式
c
1 #include <iostream>
2 #include <string>
3 #include <list>
4 using namespace std;
5
6 class Phone
7 {
8 public:
9 Phone() {}
10 virtual ~Phone() {}
11 virtual void ShowDecorate() {}
12 };
13 //具体的手机类
14 class SimplePhone : public Phone
15 {
16 private:
17 string namePhone;
18 public:
19 SimplePhone(string name) : namePhone(name) {}
20 ~SimplePhone() {}
21 void ShowDecorate() {
22 cout <<endl<<namePhone << ":" << endl;
23 }
24 };
25 //装饰类
26 class DecoratorPhone : public Phone
27 {
28 private:
29 Phone* m_phone; //要装饰的手机
30 public:
31 DecoratorPhone(Phone* phone) : m_phone(phone) {}
32 virtual void ShowDecorate() { m_phone->ShowDecorate(); }
33 };
34 //具体的装饰类
35 class DecoratorPhoneA : public DecoratorPhone
36 {
37 public:
38 DecoratorPhoneA(Phone* phone) : DecoratorPhone(phone) {}
39 void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); }
40 private:
41 void AddDecorate() { cout << "发出声音提示主人电话来了" << endl; } //增加的装饰
42 };
43 //具体的装饰类
44 class DecoratorPhoneB : public DecoratorPhone
45 {
46 public:
47 DecoratorPhoneB(Phone* phone) : DecoratorPhone(phone) {}
48 void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); }
49 private:
50 void AddDecorate() { cout << "震动提示主人电话来了" << endl; } //增加的装饰
51 };
52 //具体的装饰类
53 class DecoratorPhoneC : public DecoratorPhone
54 {
55 public:
56 DecoratorPhoneC(Phone* phone) : DecoratorPhone(phone) {}
57 void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); }
58 private:
59 void AddDecorate() { cout << "闪烁灯光提示主人电话来了" << endl; } //增加的装饰
60 };
61 int main()
62 {
63 Phone* iphone = new SimplePhone("SimplePhone");
64 Phone* dpa = new DecoratorPhoneA(iphone);
65 dpa->ShowDecorate();
66
67 Phone* phone = new SimplePhone("JarPhone");
68 Phone* dpA = new DecoratorPhoneA(phone);
69 Phone* dpb = new DecoratorPhoneB(dpA);
70 dpb->ShowDecorate();
71
72 Phone* cphone = new SimplePhone("ComplexPhone");
73 Phone* d = new DecoratorPhoneA(cphone);
74 Phone* dpB = new DecoratorPhoneB(d);
75 Phone* dpC = new DecoratorPhoneC(dpB);
76 dpC->ShowDecorate();
77
78 delete dpa;
79 delete iphone;
80
81 delete dpA;
82 delete dpb;
83 delete phone;
84
85 delete d;
86 delete dpB;
87 delete dpC;
88 delete cphone;
89 }

浙公网安备 33010602011771号