[设计模式]适配器模式--协议适配[rtsp/sip/.../.]

来源:互联网 发布:网络聊天技巧pdf 编辑:程序博客网 时间:2024/06/05 04:40

适配器模式切换协议框架,直接上代码:


// Adapter.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"//适配器模式:协议适配//类适配器模式===============================================// "ITarget"class Target{public:// Methodsvirtual void Request(int type){};};// "Adaptee"class RtspAdapter{public:// Methodsvoid RtspRequest(){printf("Called RTSP Request\n");}};class SipAdapter{public:void SipRequest(){printf("Called SIP Request\n");}};class OnvifAdapter{public:void OnvifRequest(){printf("Called Onvif Request\n");}};// "Adapter"类适配器class ProtocolAdapterClass : public RtspAdapter, public Target, SipAdapter, OnvifAdapter{public:// Implements ITarget interfacevoid Request(int type){// Possibly do some data manipulation// and then call SpecificRequest  if (type == 0){this->RtspRequest();}else if (type == 1){this->SipRequest();}else if (type == 2){this->OnvifRequest();}elseprintf("no support tpye for Request\n");}};// "Adapter"对象适配器class ProtocolAdapterObj :public Target{public:// Implements ITarget interfaceProtocolAdapterObj(int type = 0){m_type = type;if (type == 0){RtspObj = new RtspAdapter();}else if (type == 1){SipObj = new SipAdapter;}else if (type == 2){OnvifObj = new OnvifAdapter;}elseprintf("no support tpye \n");}void Request(int type){// Possibly do some data manipulation// and then call SpecificRequest  if (m_type == 0){RtspObj->RtspRequest();}else if (m_type == 1){SipObj->SipRequest();}else if (m_type == 2){OnvifObj->OnvifRequest();}elseprintf("no support tpye for Request\n");}private:RtspAdapter  *RtspObj;SipAdapter   *SipObj;OnvifAdapter *OnvifObj;int           m_type;};int main(){printf("类适配器===============\n");Target *t = new ProtocolAdapterClass();printf("RTSP:\n");t->Request(0);printf("SIP:\n");t->Request(1);printf("Onvif:\n");t->Request(2);printf("Error Type:\n");t->Request(3);printf("\n对象适配器=============\n");Target *t2 = NULL;printf("RTSP:\n");t2 = new ProtocolAdapterObj(0);t2->Request(0);delete t2;printf("SIP:\n");t2 = new ProtocolAdapterObj(1);t2->Request(1);delete t2;printf("Onvif:\n");t2 = new ProtocolAdapterObj(2);t2->Request(2);delete t2;getchar();return 0;}


0 0
原创粉丝点击