【1】什么是适配器模式?
将一个类的接口转换成客户希望的另外一个接口。
Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。
【2】适配器模式的代码示例:
代码示例如下1:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class Adaptee
6 {
7 public:
8 virtual void myRequest()
9 {
10 cout << "实际上的接口" << endl;
11 }
12 };
13
14 class Target
15 {
16 public:
17 virtual void request() = 0;
18 virtual ~Target(){}
19 };
20
21 class Adapter : public Target
22 {
23 private:
24 Adaptee adaptee;
25 public:
26 void request()
27 {
28 adaptee.myRequest();
29 }
30 };
31
32 int main()
33 {
34 Target *target = new Adapter();
35 target->request();
36 delete target;
37 return 0;
38 }
39 //Result:
40 //实际上的接口
代码示例如下2:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 class Player
6 {
7 public:
8 string name;
9 Player(string name)
10 {
11 this->name = name;
12 }
13 virtual void attack() = 0;
14 virtual void defence() = 0;
15 };
16
17 class Forwards : public Player
18 {
19 public:
20 Forwards(string name) : Player(name){}
21 void attack()
22 {
23 cout << name << "前锋进攻" << endl;
24 }
25 void defence()
26 {
27 cout << name << "前锋防守" << endl;
28 }
29 };
30
31 class Center : public Player
32 {
33 public:
34 Center(string name) : Player(name){}
35 void attack()
36 {
37 cout << name << "中锋进攻" << endl;
38 }
39 void defence()
40 {
41 cout << name << "中锋防守" << endl;
42 }
43 };
44
45 class Backwards : public Player
46 {
47 public:
48 Backwards(string name) : Player(name){}
49 void attack()
50 {
51 cout << name << "后卫进攻" << endl;
52 }
53 void defence()
54 {
55 cout << name << "后卫防守" << endl;
56 }
57 };
58 /*****************************************************************/
59 class ForeignCenter
60 {
61 public:
62 string name;
63 ForeignCenter(string name)
64 {
65 this->name = name;
66 }
67 void myAttack()
68 {
69 cout << name << "外籍中锋进攻" << endl;
70 }
71 void myDefence()
72 {
73 cout << name << "外籍中锋防守" << endl;
74 }
75 };
76 /*****************************************************************/
77 class Translator : public Player
78 {
79 private:
80 ForeignCenter *fc;
81 public:
82 Translator(string name) : Player(name)
83 {
84 fc = new ForeignCenter(name);
85 }
86 void attack()
87 {
88 fc->myAttack();
89 }
90 void defence()
91 {
92 fc->myDefence();
93 }
94 };
95 /*****************************************************************/
96 int main()
97 {
98 Player *p1 = new Center("李俊宏");
99 p1->attack();
100 p1->defence();
101
102 Translator *tl = new Translator("姚明");
103 tl->attack();
104 tl->defence();
105
106 return 0;
107 }
108 //Result:
109 /*
110 李俊宏中锋进攻
111 李俊宏中锋防守
112 姚明外籍中锋进攻
113 姚明外籍中锋防守
114 */
Good Good Study, Day Day Up.
顺序 选择 循环 总结