蜗牛的家
男儿当自强
posts - 48,  comments - 21,  trackbacks - 0
意图:
将一个类的接口转换成客户需要的另外一个接口。使得原本不兼容而不能在一起工作的类可以一起工作
适用:
你想使用一个类,而他的接口不符合你的要求
你想创建一个可复用的类,该类可以与其他不相关的类或是不可预见的类协同工作,或是使用多重继承的方法避免
UML图:
采用继承原有接口类的方式

采用组合原有接口类的方式

解析:
Adapt模式其实就是把完成同样的一个功能但是接口不能兼容的类桥接在一起使之可以在一起工作,这个模式使得复用旧的接口成为可能.
//test.h
//////////////////////////////////////////////////////////////////////////
//需要被Adapt的类
class Target
{
public:
    Target()
{}
    
virtual ~Target(){}
    
    
virtual void Request() = 0;
}
;
//与被Adapt对象存在不兼容接口的类,或是这个类与target类毫无关联,去想在同一个类中使用两个类的函数.
class Adaptee
{
public:
    Adaptee()
{}
    
~Adaptee(){}

    
void SpecialRequest();
}
;
//进行Adapt的类,聚合原有接口类
class Adapter : public Target
{
public:
    Adapter(Adaptee
* pAdaptee);
    
virtual ~Adapter();

    
virtual void Request(); //重载了接口且进行了聚合
private:
    Adaptee
* m_Adaptee;
}
;

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

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

using namespace std;
//////////////////////////////////////////////////////////////////////////
void Adaptee::SpecialRequest()
{
    cout 
<< "specialRequest of Adaptee\n";
}

Adapter::Adapter(Adaptee
* pAdaptee) : m_Adaptee(pAdaptee)
{
}

Adapter::
~Adapter()
{
    delete m_Adaptee;
    m_Adaptee 
= NULL;
}

void Adapter::Request()
{
    cout 
<< "Request of Adapter\n";
    m_Adaptee
->SpecialRequest();
}

//////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
    Adaptee 
*pAdaptee = new Adaptee;
    Target 
*pTarget = new Adapter(pAdaptee);
    pTarget
->Request();

    delete pTarget;

    system(
"pause");
    
return 0;
}



posted on 2008-08-17 02:29 黑色天使 阅读(285) 评论(0)  编辑 收藏 引用 所属分类: 设计模式

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(2)

随笔分类

随笔档案

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜