adapter pattern--适配器模式

adapter pattern,又称wrapper(包装) pattern
在软件系统中,由于应用环境的变化,常常需要将一些现存的对象放在新的环境中应用,但是新环境要求的接口是这些现存对象所不满足的。Adapter设计模式就是为了应对这种迁移的变化,以使客户系统既能利用现有对象的良好实现,同时又能满足新的应用环境所要求的接口。
“Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.” ---GoF
 
将一个类的接口转化为客户端所期望的接口。适配器模式使得原本拥有不兼容接口的类能一起“工作”。--GoF
 
适配器一般有两种形式:
第一种形式

该形式是采用继承方式实现复用Adaptee接口。
 
实例解析:
    例如有一个人看电视,现在想换台了,有一个换台请求的接口,而电视机也可以接收信号换台,它拥有一个接收信号的接口,现在很清楚这两个类之间不兼容,我们需要一个适配器来使得这两个拥有不兼容接口的类一起工作。采取继承复用的方式。
 1 class IdeaChange
 2 {
 3     public:
 4         virutal void RequestChange( )=0;
 5 };
 6 class Tv
 7 {
 8     public:
 9         void AcceptRequest( );  
10 };
11 void Tv::AcceptRequest( )
12 {
13     std::cout<<"Accept the request of ChannelChange"<<std::endl; 
14 }
15 class Adapter:public IdeaChange,private Tv
16 {
17     public:
18         void RequestChange( );
19 };
20 void Adapter::RequestChange( )
21 {
22     std::cout<<"Request for change channel"<<std::endl;
23     AcceptRequest( );
24 }
25 
26 int main(int argc,char ** argv)
27 {
28   Adapter a;
29   a.RequestChange( );
30   return 0;  
31 }

 

运行结果

第二种形式

该形式是采用组合方式实现复用Adaptee接口。
还是上面一样的实例
 1 class IdeaChange
 2 {
 3     public:
 4         virutal void RequestChange( )=0;
 5 };
 6 class Tv
 7 {
 8     public:
 9         void AcceptRequest( );  
10 };
11 void Tv::AcceptRequest( )
12 {
13     std::cout<<"Accept the request of ChannelChange"<<std::endl; 
14 }
15 class Adapter:public IdeaChange
16 {
17     public:
18         Adapter( );
19         ~Adapter( );
20         void RequestChange( );
21     private:
22         Tv* t;
23         
24 };
25 Adapter::Adapter( )
26 {
27     t=new Tv( );
28 }
29 Adapter::~Adapter( )
30 {
31     delete t;
32 }
33 void Adapter::RequestChange( )
34 {
35     std::cout<<"Request for change channel"<<std::endl;
36     t->AcceptRequest( );
37 }
38 
39 int main(int argc,char ** argv)
40 {
41   Adapter a;
42   a.RequestChange( );
43   return 0;  
44 }

 

运行结果为

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值