设为首页 加入收藏

TOP

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

 

运行结果

第二种形式

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

 

运行结果为

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇bridge pattern -- 桥接模式 下一篇prototype pattern--原型模式

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: