适配器模式(Adapter pattern)属于结构型模式,如果想用一个接口去调用另一个类的功能,可以采用适配器模式,让适配器类来实现这个接口,在适配器内里调用另一类的功能,举个例子,有两种电源接线板,它们的功能是不一样的,两者的功能我们都想用,有一个可以直接插到插座上,插上就可用了,另外一个因为不能直接插,所以不能用,为了另外一个也能用,我们就需要一个转换插座,有了这个转换插座,这个不兼容的电源接线板也就能用了,这个转换插座就是适配器类。
下面是适配器模式的C++实现,代码可到本人github网页下载:设计模式例子
/*
* Example of 'SingleTon' design pattern.
* Copyright (C) 2016 Leo Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
using namespace std;
class CTarget
{
public:
virtual void GeneralFunc()
{
cout<<"General function!"<<endl;
};
};
class CAdaptee
{
public:
void SpecialFunc()
{
cout<<"Special function!"<<endl;
};
};
class CAdapter:public CTarget
{
public:
CAdaptee* cp_adaptee;
public:
CAdapter(CAdaptee* p_adaptee)
{
cp_adaptee=p_adaptee;
};
public:
void GeneralFunc()
{
cp_adaptee->SpecialFunc();
};
};
void main()
{
CTarget* cp_target=new CTarget();
CAdaptee* cp_adaptee=new CAdaptee();
CTarget* cp_adapt=new CAdapter(cp_adaptee);
cp_target->GeneralFunc();
cp_adapt->GeneralFunc();
};
依据我们前面的比喻,CTarget就是其中的一类电源接线板,CAdaptee就是另外一种电源接线板,CAdapter就是转换头,有了这个转换头,我们就可用统一的接口用这两种接线板了,例如,其中的一个可以直接插到墙上,另外一个通过一个转接头也可以插到墙上用。