结构型模式之适配器模式(Adapter Pattern)与外观模式(Facade Pattern)

来源:互联网 发布:淘宝食品经营许可 编辑:程序博客网 时间:2024/05/02 04:17

  

适配器模式定义:将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。

   适配器模式的工作是将一个接口转换成另一个。如果让一个适配器包装多个被适配者就是Façade 模式。

对象适配器类图:

 


类适配器:


对象适配器利用组合的方式将请求传送给被适配者。类适配器采用多重继承来实现。Adapter继承了Target和Adaptee

 

 

 

适配器与装饰模式看起来类似,都是通过委托来包装对象的行为或责任,但是它们的意图差异颇大。

 

适配器模式:将一个接口转成另一接口。

外观模式:让接口更简单,它将一个或数个类的复杂的一切都隐藏在背后。

装饰模者式:不改变接口,但加入职责。

 

外观模式定义:提供了一个统一的接口,用来访问子系统中的一群接口。外观定义了一个高层接口,让子系统更容易使用。

外观模式提供简化的接口的同时,依然将系统的功能暴露出来,以供需要的人使用。外观模式与适配器的不同点在于他们的意图,不能从他们包装多少个类来判别,它们都可以包装许多类,但是外观模式的意图是简化接口,而适配器的意图是将接口转换成不同的接口符合客户的期望。


适配器模式的C++实现:

Adapter.h头文件

#ifndef _ADAPTER_H_#define _ADAPTER_H_#include<iostream>using namespace std;class Target{public:   Target();virtual ~Target();virtual void Request();};class Adaptee{public:Adaptee();~Adaptee();void SpecificRequest();};//类适配器,通过继承来实现class Adapter:public Target,private Adaptee{public:Adapter();~Adapter();void Request();};//对象适配器,通过组合实现class OAdapter:public Target{public:OAdapter(Adaptee * ade);~OAdapter();void Request();protected:private:Adaptee * _ade;};#endif

Adapter.CPP

#include "Adapter.h"Target::Target(){}Target::~Target(){ }void Target::Request(){cout<<"Target::Request"<<endl;}Adaptee::Adaptee(){}Adaptee::~Adaptee(){}void Adaptee::SpecificRequest(){cout<<"Adaptee::SpecificRequest"<<endl;}//类适配器实现Adapter::Adapter(){}Adapter::~Adapter(){}void Adapter::Request(){this->SpecificRequest();}//对象适配器实现OAdapter::OAdapter(Adaptee *ade){this->_ade=ade;}OAdapter::~OAdapter(){}void OAdapter::Request(){_ade->SpecificRequest();}

主函数main.CPP

#include "Adapter.h"#include <iostream>using namespace std;int main(int argc,char* argv[]){Adaptee* ade = new Adaptee;//对象适配器Target* adt = new OAdapter(ade);adt->Request();//类适配器Target* cadt=new Adapter;cadt->Request();return 0;}



复制搜索
原创粉丝点击