适配器模式

适配器模式。将一个类的接口转换成客户希望的另外一个接口。

Adapter模式使得原本因为接口不兼容而不能一起工作的那些类能够一起工作。

应用场景:系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类。可是接口又与复用环境要求不一致的情况。

代码实现:
//Adapter.h
#include "stdafx.h"
#include <iostream>

class Adaptee
{
public:
	void Request()
	{
		std::cout << "实际要使用的类方法!

" << std::endl; } }; class Target { public: virtual ~Target(){} virtual void Operator() = 0; }; class Adapter :public Target { private: Adaptee* m_Adaptee = new Adaptee(); public: virtual void Operator() { m_Adaptee->Request(); } };


// AdapterPattern.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Adapter.h"


int _tmain(int argc, _TCHAR* argv[])
{
	Target* target = new Adapter();
	target->Operator();

	getchar();
	return 0;
}


posted on 2017-07-07 19:03  wgwyanfs  阅读(102)  评论(0编辑  收藏  举报

导航