适配器模式:将一个类的接口,转换成客户期望的另一个接口。适配器让原本不兼容的类可以合作无间。
类图为:
举一个例子,客户需要一只鸭子(Target),但是手头只有一只火鸡(Adaptee),那么这只火鸡(Adaptee)就可通过适配器(Adapter)伪装成一只鸭子(Target)供客户使用。
看代码:
adapter.h
#pragma once
#include <iostream>
using namespace std;
//鸭子基类
class Duck
{
public:
Duck() {}
virtual ~Duck() {}
virtual void quack() = 0;
virtual void fly() = 0;
};
//绿头鸭
class MallardDuck : public Duck
{
public:
MallardDuck() {}
~MallardDuck() {}
void quack() { cout<<"Quack"<<endl; }
void fly() { cout<<"I'm flying"<<endl;}
};
//火鸡基类
class Turkey
{
public:
Turkey() {}
virtual ~Turkey() {}
virtual void gobble() = 0;
virtual void fly() = 0;
};
//街头火鸡
class WildTurkey : public Turkey
{
public:
WildTurkey() {}
~WildTurkey() {}
void gobble() { cout<<"Gobble gobble"<<endl; }
void fly() { cout<<"I'm flying a short distance"<<endl;}
};
//适配器
class TurkeyAdapter : public Duck
{
private:
Turkey *turkey;
public:
TurkeyAdapter(Turkey *turkey) : turkey(turkey) {}
~TurkeyAdapter() {}
void quack() { turkey->gobble(); }
void fly() { turkey->fly(); }
};
测试:
#include "adapter.h"
#include <cstdlib>
using namespace std;
void testDuck(Duck *duck)
{
duck->quack();
duck->fly();
}
int main()
{
MallardDuck *duck = new MallardDuck();
WildTurkey *turkey = new WildTurkey();
Duck *turkeyAdapter = new TurkeyAdapter(turkey);
cout<<"The Turkey says..."<<endl;
turkey->gobble();
turkey->fly();
cout<<"The duck says..."<<endl;
testDuck(duck);
cout<<"The TurkeyAdapter says..."<<endl;
testDuck(turkeyAdapter);
system("pause");
return 0;
}
结果: