您的位置:首页 > 其它

设计模式-结构型-适配器

2017-10-07 15:46 120 查看
#pragma once

#ifndef ADAPTER_H

#define ADAPTER_H

// 需要被Adapt 的类
class Target
{
public:
Target(){}
virtual ~Target() {}
virtual void Request() = 0;
};

// 与被Adapt 对象提供不兼容接口的类
class Adaptee
{
public:
Adaptee(){}
~Adaptee(){}
void SpecialRequest();
};

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

private:
Adaptee* m_pAdptee;
};

#endif

#include "StdAfx.h"
#include "adapter_impl.h"

#include <iostream>

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

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

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

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

// Adapter.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include "adapter_impl.h"
#include <stdlib.h>
// 将一个类的接口转换成客户希望的另外一个接口。Adapt 模式使得原本由于接
// 口不兼容而不能一起工作的那些类可以一起工作。
int _tmain(int argc, _TCHAR* argv[])
{
Adaptee *pAdaptee = new Adaptee; //新加入的不兼容接口

Target *pTarget = new Adapter(pAdaptee); //已定义接口

pTarget->Request();

delete pTarget;

system("pause");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: