目录
一、介绍
适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。一般分为前两种模式,第三种较为特殊。
1.1、对象适配器模式
在这种适配器模式中,适配器容纳一个它包裹的类的实例。在这种情况下,适配器调用被包裹对象的物理实体。
对象适配器”通过组合除了满足“用户期待接口”还降低了代码间的不良耦合。在工作中推荐使用“对象适配”。
1.2、类适配器模式
这种适配器模式下,适配器继承自已实现的类(一般多重继承)。
当客户在接口中定义了他期望的行为时,我们就可以应用适配器模式,提供一个实现该接口的类,并且扩展已有的类,通过创建子类来实现适配。
1.3、缺省适配器模式
缺省适配器模式是一种特殊的适配器模式,但这个适配器是由一个抽象类实现的,并且在抽象类中要实现目标接口中所规定的所有方法,但很多方法的实现都是“平庸”的实现,也就是说,这些方法都是空方法。而具体的子类都要继承此抽象类。
二、使用场景
1、当想使用一个已存在的类,而它的接口不符合需求时。
2、你想创建一个可复用的类,该类可以与其他不相关的类或不可预见的类协同工作。
3、你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口,对象适配器可以适配它的父接口。
三、要点
3.1、对象适配器
1、有的时候,你会发现,去构造一个 Adaptee 类型的对象不是很容易。
2、当 Adaptee 中添加新的抽象方法时,Adapter 类不需要做任何调整,也能正确的进行动作。
3、可以使用多态的方式在 Adapter 类中调用 Adaptee 类子类的方法。
由于对象适配器的耦合度比较低,所以在很多的书中都建议使用对象适配器。在我们实际项目中,也是如此,能使用对象组合的方式,就不使用多继承的方式。
3.2、类适配器
1、由于 Adapter 直接继承自 Adaptee 类,所以,在 Adapter 类中可以对 Adaptee 类的方法进行重定义。
2、如果在 Adaptee 中添加了一个抽象方法,那么 Adapter 也要进行相应的改动,这样就带来高耦合。
3、如果 Adaptee 还有其它子类,而在 Adapter 中想调用 Adaptee 其它子类的方法时,使用类适配器是无法做到的。
四、样例
4.1、对象适配器样例
// 对象适配器样例
#include<iostream>
using namespace std;
// "ITarget":目标接口
class Target
{
public:
// Methods
virtual void Request(){};
};
// "Adaptee":适配者
class Adaptee
{
public:
// Methods
void SpecificRequest()
{
cout << "Called SpecificRequest()" << endl;
}
};
// "Adapter":适配器
class Adapter : public Target
{
private:
Adaptee *adaptee;
public:
Adapter()
{
adaptee = new Adaptee();
}
// Implements ITarget interface
void Request()
{
// Possibly do some data manipulation
// and then call SpecificRequest
adaptee->SpecificRequest();
}
};
int main()
{
// Create adapter and place a request
Target *t = new Adapter();
t->Request();
return 0;
}
4.2、类适配器模式样例
// 类适配器Demo
#include<iostream>
using namespace std;
// "ITarget"
class Target
{
public:
// Methods
virtual void Request(){};
};
// "Adaptee"
class Adaptee
{
public:
// Methods
void SpecificRequest()
{
cout << "Called SpecificRequest()" << endl;
}
};
// "Adapter"
class Adapter : public Adaptee, public Target
{
public:
// Implements ITarget interface
void Request()
{
// Possibly do some data manipulation
// and then call SpecificRequest
this->SpecificRequest();
}
};
int main()
{
// Create adapter and place a request
Target *t = new Adapter();
t->Request();
return 0;
}
4.3、缺省适配器模式样例
// 缺省适配器模式
#include<iostream>
using namespace std;
class Target {
public:
virtual void f1(){};
virtual void f2(){};
virtual void f3(){};
};
class DefaultAdapter : public Target
{
public:
void f1() {
}
void f2() {
}
void f3() {
}
};
class MyInteresting :public DefaultAdapter
{
public:
void f3(){
cout << "呵呵,我就对f3()方法感兴趣,别的不管了!" << endl;
}
};
int main()
{
// Create adapter and place a request
Target *t = new MyInteresting();
t->f3(); // 呵呵,我就对f3()方法感兴趣,别的不管了!
return 0;
}
五、优缺点
优点
1、可以让任何两个没有关联的类一起运行
2、提高了类的复用
3、增加了类的透明度
4、灵活性好
缺点
过多地使用适配器,会让系统非常零乱,不利于整体把控。