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

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


// 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;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值