适配器模式将一个类接口,转换成客户期望的另一个接口,让原本接口不兼容的类可以合作无间。
#ifndef __ADAPTER_H
#define __ADAPTER_H
#include<iostream>
using namespace std;
class Duck
{
public:
virtual void quack() = 0;
virtual void fly() = 0;
};
class MallardDuck :public Duck
{
public:
void quack()
{
cout << "Quack" << endl;
}
void fly()
{
cout << "I'm flying" << endl;
}
};
class Turkey
{
public:
virtual void gobble() = 0;
virtual void fly() = 0;
};
class WildTurkey :public Turkey
{
public:
void gobble()
{
cout << "Gobble gobble" << endl;
}
void fly()
{
cout << "I'm flying" << endl;
}
};
class TurkeyAdapter :public Duck
{
private:
Turkey *turkey;
public:
TurkeyAdapter(Turkey *turkey) :turkey(turkey){}
void quack()
{
turkey->gobble();
}
void fly()
{
turkey->fly();
}
};
#endif
#include"adapter.h"
void testDuck(Duck* duck)
{
duck->quack();
duck->fly();
}
int main()
{
MallardDuck* mallarDuck = new MallardDuck();
WildTurkey* wildTurkey = new WildTurkey();
Duck* turkeyAdapter = new TurkeyAdapter(wildTurkey);
cout << "The Turkey says..." << endl;
wildTurkey->gobble();
wildTurkey->fly();
cout << "The Duck says..." << endl;
testDuck(mallarDuck);
cout << "The TurkeyAdapter says..." << endl;
testDuck(turkeyAdapter);
}