适配器模式
作者:互联网
定义:将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。
例如之前举例子的鸭子,鸭子基类可以飞,可以叫。但是火鸡不属于鸭子,它可以叫,但是飞的距离不如鸭子远,方法里飞行定义也不一样,这时,就需要写个适配器来把火鸡伪装成鸭子。
示例
class Duck
{
public:
virtual void fly() = 0;
virtual void quake() = 0;
};
class Turkey
{
public:
void turkeyFly()
{
cout << "火鸡飞行"<<endl;
};
void turkeyquake()
{
cout << "火鸡叫"<<endl;
};
};
class TurkeyAdpater:public Duck
{
public:
TurkeyAdpater(Turkey* pTur)
{
m_pT = pTur;
};
virtual void fly()
{
//火鸡飞行距离短,让它飞三次,装作鸭子飞
for (int i = 0; i< 3; i++)
{
m_pT->turkeyFly();
}
};
virtual void quake()
{
m_pT->turkeyquake();
};
private:
Turkey* m_pT;
};
int main()
{
Duck* pDuck = nullptr;
Turkey* pTurkey = new Turkey;
pDuck = new TurkeyAdpater(pTurkey);
pDuck->fly();
pDuck->quake();
delete pTurkey;
delete pDuck;
return 0;
}
标签:Turkey,pDuck,适配器,模式,pTurkey,鸭子,void 来源: https://blog.csdn.net/a_freshbird/article/details/120643506