用代码跟UML图化解设计模式之《适配器模式》

用代码和UML图化解设计模式之《适配器模式》

所谓适配器模式,就是为了解决或者叫融合系统之间的差异,通过提供一个类,来融合这种差异。

这让我想起来读《UNIX 编程艺术》里一个名词  就是胶合层。

 

胶合层也算是一种适配上层鱼下层之间的差异和出现的一种处理方式。   这个是解决系统差异的一个具体表现,

 

下面上图吧

 

用代码跟UML图化解设计模式之《适配器模式》

 

代码片段

 

// Adapter.cpp : 定义控制台应用程序的入口点。
///************************************************************************/
/* @filename   Adapter.cpp
   @author       wallwind
   @createtime    2012/10/222 9:36
   @function      适配器模式
   @email       wochenglin@qq.com
*/
/************************************************************************/


#include "stdafx.h"
#include <iostream>

using namespace std;

class Base
{
public:
	Base(){}
	virtual ~Base(){};

	virtual void doAction()=0;

};

class Outer
{
public:
	Outer(){}
	~Outer(){}
	
	void exec()
	{
		cout<<"Outer:exec"<<endl;
	}
};

class Adapter:public Base
{
public:
	Adapter(Outer* outer)
		:m_outer(outer)
	{
	}
	virtual ~Adapter()
	{
		if (m_outer!=NULL)
		{
			delete m_outer;
		}
	}
	
	void doAction()
	{
		cout<<"Adapter:doAction"<<endl;
		m_outer->exec();
	}
private:
	Outer* m_outer;

};
int _tmain(int argc, _TCHAR* argv[])
{
	Outer *out =new Outer;
	Base *adapter =new Adapter(out);

	adapter->doAction();

	if (adapter!=NULL)
	{
		delete adapter;
	}
	return 0;
}


输出结果:

用代码跟UML图化解设计模式之《适配器模式》

更多文章,欢迎访问:

http://blog.csdn.net/wallwind