1 定义:
[color=red]将一个类的接口转换成客户希望的另外一个接口。Apapter模式是的原本由于接口不兼容而不能一起工作的那些类可以一起工作。实际上有两种适配器,对象适配器和类适配器。[/color]
属于结构型模式,需要有Adaptee(被适配者)和Adaptor(适配器)两个身份.
比如说,我们买的欧版手机,一般都需要一个适配器转换成国内的接口,这就是实例。
[img]http://t25-1.yunpan.360.cn/p/800-600.bdc44358698f4f2283884ce94afcda68d9ebba81.f228c9.jpg?t=7f39af56fd4daeef611a2c8707d9ce5b&d=20130822[/img]
标准范例如下
[color=red]将一个类的接口转换成客户希望的另外一个接口。Apapter模式是的原本由于接口不兼容而不能一起工作的那些类可以一起工作。实际上有两种适配器,对象适配器和类适配器。[/color]
属于结构型模式,需要有Adaptee(被适配者)和Adaptor(适配器)两个身份.
比如说,我们买的欧版手机,一般都需要一个适配器转换成国内的接口,这就是实例。
[img]http://t25-1.yunpan.360.cn/p/800-600.bdc44358698f4f2283884ce94afcda68d9ebba81.f228c9.jpg?t=7f39af56fd4daeef611a2c8707d9ce5b&d=20130822[/img]
//Adapter
//
class Duck
{
public:
virtual ~Duck(){}
virtual void quack() = 0;
virtual void fly() = 0;
};
//
class MallardDuck : public Duck
{
public:
virtual void quack()
{
cout << "Quack" << endl;
}
virtual void fly()
{
cout << "I'm flying" << endl;
}
};
//
class Turkey
{
public:
virtual void gobble() = 0;
virtual void fly() = 0;
};
//
class WildTurkey : public Turkey
{
public:
virtual void gobble()
{
cout << "Gobble gobble" << endl;
}
virtual void fly()
{
cout << "I'm flying a short distance." << endl;
}
};
//
class TurkeyAdapter : public Duck
{
public:
TurkeyAdapter(Turkey* turkey)
:m_Turkey(NULL)
{
//if (m_Turkey != NULL)
//{
// delete m_Turkey;
// m_Turkey = NULL;
//}
m_Turkey = turkey;
}
virtual ~TurkeyAdapter()
{
//if (m_Turkey != NULL)
//{
// delete m_Turkey;
//}
}
virtual void quack()
{
assert(m_Turkey != NULL);
m_Turkey->gobble();
}
virtual void fly()
{
assert(m_Turkey != NULL);
for (int i = 0; i < 5; i++)
{
m_Turkey->fly();
}
}
private:
Turkey* m_Turkey;
};
//
class DuckTestDrive
{
public:
void run()
{
MallardDuck* duck = new MallardDuck();
WildTurkey* turkey = new WildTurkey();
Duck* turkeyAdapter = new TurkeyAdapter(turkey);
cout << "The Turkey says ..." << endl;
turkey->gobble();
cout << "\nThe Duck says ..." << endl;
testDuck(duck);
cout << "\nThe TurkeyAdapter says ..." << endl;
testDuck(turkeyAdapter);
delete duck;
delete turkey;
delete turkeyAdapter;
}
private:
void testDuck(Duck* duck)
{
assert(duck != NULL);
duck->quack();
duck->fly();
}
};
标准范例如下
#include <iostream>
using namespace std;
class Target
{
public:
Target()
{
}
virtual ~Target()
{
}
virtual void Request()
{
cout<<"Target::Request"<<endl;
}
};
class Adaptee
{
public:
Adaptee(){}
~Adaptee(){}
void SpecificRequest()
{
cout<<"Adaptee::SpecificRequest"<<endl;
}
};
class Adapter : public Target
{
public:
Adapter(Adaptee *ade)
{
this->_ade = ade;
}
~Adapter(){}
void Request()
{
_ade->SpecificRequest();
}
private:
Adaptee *_ade;
};
int main(int argc, char *argv[])
{
Adaptee *ade = new Adaptee;
Target *adt = new Adapter(ade);
adt->Request();
return 0;
}