emptysoul

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  25 Posts :: 0 Stories :: 23 Comments :: 0 Trackbacks

常用链接

留言簿(18)

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜

适配器模式(Adapter)的目标是将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作,其分为类模式及对象模式,结构图如下:
类模式:

对象模式:

假设现在我们的系统中使用了大量的图表功能用来统计数据,图表都从Chart类派生,并且所有的显示都调用Show接口,由于一些原因,我们现在需要使用第三提供的图表控件(BeautyChart),它只提供了接口给我们,并且其显示方式改变了,为了使原来的接口与新控件接口一同工作,这时就可提供一个适配器,用来将新控件的接口适配成我们所期望的原来的接口,结构图如下:


实现代码:

//Chart.h
class Chart  
{
public:
    
virtual ~Chart();

    
virtual void Show();
protected:
    Chart();
};

//Chart.cpp
#include "stdafx.h"
#include 
"Chart.h"
#include 
<iostream>

using namespace std;

Chart::Chart()
{
    
}

Chart::
~Chart()
{

}

void Chart::Show()
{
    cout 
<< "使用原始方法画图表" << endl;
}

//BeautyChart.h
class BeautyChart  
{
public:
    BeautyChart();
    
virtual ~BeautyChart();

    
void DrawChart();
};

//BeautyChart.cpp
#include "stdafx.h"
#include 
"BeautyChart.h"
#include 
<iostream>

using namespace std;

BeautyChart::BeautyChart()
{

}

BeautyChart::
~BeautyChart()
{

}

void BeautyChart::DrawChart()
{
    cout 
<< "使用新的控件画图表" << endl;
}

//Adapter.h
#include "Chart.h"

class BeautyChart;
class Adapter : public Chart
{
public:
    Adapter();
    Adapter(BeautyChart
*);
    
virtual ~Adapter();

    
void Show();
private:
    BeautyChart
* m_pBeautyChart;
};

//Adapter.cpp
#include "stdafx.h"
#include 
"Adapter.h"
#include 
"BeautyChart.h"

Adapter::Adapter()
{
    m_pBeautyChart 
= NULL;
}

Adapter::Adapter(BeautyChart
* pBeautyChart)
{
    m_pBeautyChart 
= pBeautyChart;
}

Adapter::
~Adapter()
{
    
if(m_pBeautyChart != NULL)
    {
        delete m_pBeautyChart;
        m_pBeautyChart 
= NULL;
    }
}

void Adapter::Show()
{
    
if(m_pBeautyChart != NULL)
    {
        m_pBeautyChart
->DrawChart();
    }
    
else
    {
        Chart::Show();
    }
}

//main.cpp
#include "stdafx.h"
#include 
"Chart.h"
#include 
"BeautyChart.h"
#include 
"Adapter.h"

int main(int argc, char* argv[])
{
    Chart
* pChart = new Adapter();
    pChart
->Show();

    pChart 
= new Adapter(new BeautyChart);
    pChart
->Show();

    
return 0;
}

最后输出为:
使用原始方法画图表
使用新的控件画图表

从输出可以看出,加入适配器后,既可以用原来的方式画图表,又可以用新控件来工作。

posted on 2009-02-10 15:23 emptysoul 阅读(325) 评论(0)  编辑 收藏 引用

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