[结构型模式] head first 设计模式之适配器模式(Adapter)

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]



//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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值