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

来源:互联网 发布:工程施工进度计划软件 编辑:程序博客网 时间:2024/05/16 06:41
#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;}