走进设计模式之——适配器模式 (Adapter)
2014-06-06 11:26
162 查看
1. 概述
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。2. 解决的问题
即Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。3. 模式结构
Adapter模式的两种类别:类模式和对象模式。Adapter模式典型的结构图为。图1 AdapterPattern(类模式)结构图
图2 AdapterPattern(对象模式)结构图
模式中的角色
目标接口(Target):
客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
需要适配的类(Adaptee):
需要适配的类或适配者类。
适配器(Adapter):
通过包装一个需要适配的对象,把原接口转换成目标接口。
4.实现
下面是模式简单实现的关键代码。(完全代码,见下载)4.1 类适配器
<span style="font-family:Microsoft YaHei;">classTarget { public: Target(); virtual ~Target(); virtual void Request(); }; classAdaptee { public: Adaptee(); ~Adaptee(); void SpecificRequest(); }; classAdapter: public Target, private Adaptee { public: Adapter(); ~Adapter(); void Request(); }; voidAdapter::Request() { this->SpecificRequest(); }</span>
4.2 对象适配器
<span style="font-family:Microsoft YaHei;">classTarget { public: Target(); virtual ~Target(); virtual void Request(); }; classAdaptee { public: Adaptee(); ~Adaptee(); void SpecificRequest(); }; classAdapter:public Target { public: Adapter(Adaptee* ade); ~Adapter(); void Request(); private: Adaptee *_ade; }; Adapter::Adapter(Adaptee*ade) { this->_ade = ade; } voidAdapter::Request() { _ade->SpecificRequest(); }</span>
相关文章推荐
- 乐在其中设计模式(C#) - 适配器模式(Adapter Pattern)
- C# 设计模式 之 适配器模式(Adapter)
- 白话设计模式--结构型模式之 适配器模式(Adapter)
- 设计模式之--适配器模式(adapter)
- 设计模式学习5 -- 适配器模式(Adapter)
- 结构型设计模式---Adapter模式(适配器模式)
- .NET设计模式(8):适配器模式(Adapter Pattern)
- 设计模式之--适配器模式(adapter)
- 设计模式学习----Adapter(适配器模式)
- 设计模式(7)-适配器模式(Adapter)
- .NET设计模式-适配器模式(Adapter Pattern)
- 设计模式学习笔记十一:适配器模式(Adapter Pattern)
- 乐在其中设计模式(C#) - 适配器模式(Adapter Pattern)
- 解读设计模式----适配器模式(Adapter Pattern),麻雀飞上枝头真能成凤凰?
- 设计模式1-适配器模式(Adapter)
- 设计模式 - Adapter Pattern(适配器模式)
- 解读设计模式----适配器模式(Adapter Pattern),麻雀飞上枝头真能成凤凰?
- 设计模式学习笔记(3)——适配器模式(Adapter Pattern)
- 设计模式学习笔记1 - Adapter(适配器模式)
- 设计模式(9)-适配器模式(Adapter)