http://blog.youkuaiyun.com/lcl_data/article/details/8780140
适配器模式
特点:将一个类的接口转换成客户希望的另一个接口。通过适配器模式可以改变已有类的接口形式。
涉及到的角色:
目标(Target)角色:这是客户所期待的接口。
源(Adaptee)角色:需要适配的类。
适配器(Adapter)角色:把源接口转换成目标接口。这一角色必须是类。
适配器模式有类适配器和对象适配器两种模式,我们就这两类分别给出例子。
class Target18v{
public:
virtual void Use_18v()=0;
};
class Adaptee220v{
public:
void Use_220v(){
cout<<"welcome 220"<<endl;
}
};
//适配器模式有类适配器和对象适配器两种模式
class Adapter:public Target18v,public Adaptee220v {//类适配器,多重继承
public:
void Use_18v(){
cout<<"Adapter 220v"<<endl;
Use_220v();
}
};
class Adapter1:public Target18v {//对象配器,内部关联
public:
Adapter1(Adaptee220v* ad){
adaptee=ad;
}
void Use_18v(){
cout<<"Adapter 220v1"<<endl;
adaptee->Use_220v();
}
private:
Adaptee220v* adaptee;
};
int main(){
Adaptee220v* t=new Adaptee220v;
Target18v* p=new Adapter;
p->Use_18v();
Target18v* p1=new Adapter1(t);
p1->Use_18v();
delete t;
delete p;
delete p1;
return 0;
}