适配器模式:将一个类的接口,转换成用户期望的接口
对象适配器模式
C++示例代码如下:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
/*
* CONTENTS: DESIGN PATTERN, OBJECT ADAPTER PATTERN
* AUTHOR: YAO H. WANG
* TIME: 2013-11-3 15:21:42
* EDITION: 1
* LINK: http://blog.csdn.net/yaohwang
*
* ALL RIGHTS RESERVED!
*/
//鸭子
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 a short distance" << endl;
}
};
//适配器
class TurkeyAdapter: public Duck
{
private:
Turkey *turkey;
public:
TurkeyAdapter(Turkey *turkey)
{
this->turkey = turkey;
}
void quack()
{
turkey->gobble();
}
void fly()
{
for(int i = 0; i < 5; ++i)
turkey->fly();
}
};
//测试
void testDuck(Duck *duck)
{
duck->quack();
duck->fly();
}
void main()
{
MallardDuck *duck = new MallardDuck();
WildTurkey *turkey = new WildTurkey();
Duck *turkeyAdapter = new TurkeyAdapter(turkey);
cout << "The Turkey says..." << endl;
turkey->gobble();
turkey->fly();
cout << "\nThe Duck says..." << endl;
testDuck(duck);
cout << "\nThe TurkeyAdapter says..." << endl;
testDuck(turkeyAdapter);
delete duck;
delete turkey;
delete turkeyAdapter;
}