适配器模式切换协议框架,直接上代码:
// Adapter.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
//适配器模式:协议适配
//类适配器模式===============================================
// "ITarget"
class Target
{
public:
// Methods
virtual void Request(int type){};
};
// "Adaptee"
class RtspAdapter
{
public:
// Methods
void 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 interface
void 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();
}
else
printf("no support tpye for Request\n");
}
};
// "Adapter"对象适配器
class ProtocolAdapterObj :public Target
{
public:
// Implements ITarget interface
ProtocolAdapterObj(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;
}
else
printf("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();
}
else
printf("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;
}