软件设计⑩①|装饰模式

软件设计⑩①|装饰模式

一、类图

软件设计⑩①|装饰模式

二、效果

软件设计⑩①|装饰模式

三、代码

 1 #include<iostream>
 2 using namespace std;
 3 
 4 //公共抽象类
 5 class Phone {
 6 public:
 7     virtual void voice() {}
 8 };
 9 
10 //SimplePhone
11 class SimplePhone :public Phone {
12 private:
13     string phone;//手机
14 public:
15     SimplePhone(string phone) :phone(phone) {}
16     void voice() {
17         cout << "来电声音提示" << endl;
18     }
19 };
20 
21 //装饰类
22 class PhoneDecorator :public Phone {
23 private:
24     Phone* phone;//要装饰的手机
25 public:
26     PhoneDecorator(Phone* phone) :phone(phone) {}
27     virtual void voice() {
28         phone->voice();
29     }
30 };
31 
32 //ComplexPhone
33 class ComplexPhone :public PhoneDecorator {
34 public:
35     ComplexPhone(Phone* phone) :PhoneDecorator(phone) {}
36     void voice() {
37         cout << "来电声乐提示" << endl;
38     }
39     void shake() {
40         cout << "来电振动提示" << endl;
41     }
42     void light() {
43         cout << "来电灯光提示" << endl;
44     }
45 };
46 
47 //JarPhone
48 class JarPhone :public PhoneDecorator {
49 public:
50     JarPhone(Phone* phone) :PhoneDecorator(phone) {}
51     void voice() {
52         cout << "来电声乐提示" << endl;
53     }
54     void shake() {
55         cout << "来电振动提示" << endl;
56     }
57 };
58 
59 int main() {
60     cout << "SimplePhone" << endl;
61     Phone* phone = new SimplePhone("SimplePhone");
62     phone->voice();
63     cout << endl;
64     cout << "JarPhone" << endl;
65     JarPhone* phone1 = new JarPhone(phone);
66     phone1->voice();
67     phone1->shake();
68     cout << endl;
69     cout << "ComplexPhone" << endl;
70     ComplexPhone* phone2 = new ComplexPhone(phone);
71     phone2->voice();
72     phone2->shake();
73     phone2->light();
74 }

参考链接:https://blog.****.net/wuzhekai1985/article/details/6672614

上一篇:DOM实现简单手机号验证


下一篇:设计模式の工厂模式