定义
适配器将一个类的接口转换成客户希望的另外一个接口,该模式使得原来由于接口不兼容而不能一起工作的那些类可以一起工作。
结构
类适配器包含两种结构:
1.使用多重继承对一个接口与另一个接口进行匹配:如下图所示。

2.依赖于对象组合,如下图所示。

理解
在这么几种情况下可以使用类适配器模式:
1.你想使用一个已经存在的类,而它的接口不符合你的需求。
2.你想创建一个可以复用的类,该类可以与其他不相关的类(那些接口可能不一定兼容的类)或不可预见的类协同工作。
3.你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。(仅使用于对象适配器)
应用
1.ET++Draw通过使用一个TextShape适配器类的方式复用了ET++中的一些类,并将它们用于正文编辑。
2.InterView2.6中也使用了诸如类适配器和对象适配器的概念。
代码
- #include <iostream>
- using namespace std;
-
-
- class stack
- {
- public:
- int pop(){}
- void posh(int ){}
- int get_size(){}
- bool is_empty(){}
- private:
-
- };
-
-
- class queue
- {
- public:
- int q_push(){}
- void q_pop(){}
- int front(){}
- int back(){}
- int get_size(){}
- bool is_empty(){}
- private:
-
- };
-
-
- class q_stack : public stack, private queue
- {
- public:
- int pop()
- {
-
- queue::q_pop();
- }
- void push()
- {
- queue::q_push();
- }
- int get_size()
- {
- return queue::get_size();
- }
- bool is_empty()
- {
- return queue::is_empty();
- }
- private:
-
- };
|