设计模式(6)——适配器 Adapter

来源:互联网 发布:韩宜淘宝旗舰店 编辑:程序博客网 时间:2024/06/05 06:06

目录:

设计模式学习笔记首页
设计模式(1)——抽象工厂 AbstractFactory
设计模式(2)——生成器 Builder
设计模式(3)——工厂方法 Factory Method
设计模式(4)——原型 Prototype
设计模式(5)——单例 Singleton
设计模式(6)——适配器 Adapter
设计模式(7)——桥接 Bridge
设计模式(8)——组合 Composite
设计模式(9)——装饰 Decorator
设计模式(10)——外观 Facade
设计模式(11)——享元 Flyweight
设计模式(12)——代理 Proxy
设计模式(13)——职责链 Chain Of Responsibility
设计模式(14)——命令 Command
设计模式(15)——解释器 Interpreter
设计模式(16)——迭代器 Iterator
设计模式(17)——中介者 Mediator
设计模式(18)——备忘录 Memento
设计模式(19)——观察者 Observer
设计模式(20)——状态 State
设计模式(21)——策略 Strategy
设计模式(22)——模板方法 Template Method
设计模式(23)——访问者 Visitor

六、Adapter(适配器模式,别名 Wrapper 包装器模式,类对象结构型模式)

1. 问题:

  当系统需要使用一个接口,而此接口与系统正在使用的接口不兼容时。

2. 意图:

  将一个类的接口转换成客户希望的另外一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

3. 适用:

  想使用一个已经存在的类,而它的接口不符合需求。

4. 类图:

image

5. 中间层思考:

  适配器模式需要使用的类与已有类之间加了一个中间层 —— Adapter,来解决接口不兼容的问题。

6. C++实现:

  Adapter 模式根据实现方式不同,有类模式(继承)的适配器和对象(组合)模式的适配器。
1. 编写一个类 Adapter,包含一个与系统兼容的函数 Request
2. 让类 Adapter 继承要适配的类 Adaptee 或 组合一个 Adaptee 对象
3. 函数 Request 调用 Adaptee 中的 具体函数

Adapter.h

// Adapter.h#pragma onceclass Target {public:    Target();    virtual ~Target();    virtual void Request();protected:private:};class Adaptee {public:    Adaptee();    ~Adaptee();    void SpecificRequest();protected:private:};class Adapter : public Target, private Adaptee {public:    Adapter();    ~Adapter();    void Request();protected:private:};

Adapter.cpp

// Adapter.cpp#include "Adapter.h"#include "Adapter.h"#include <iostream>Target::Target(){}Target::~Target(){}void Target::Request() {    std::cout << "Target::Request" << std::endl;}Adaptee::Adaptee() {}Adaptee::~Adaptee() {}void Adaptee::SpecificRequest() {    std::cout << "Adaptee::SpecificRequest" << std::endl;}Adapter::Adapter() {}Adapter::~Adapter() {}void Adapter::Request() {    this->SpecificRequest();}

main.cpp

// main.cpp#include "Adapter.h"#include <iostream>using namespace::std;int main(int argc, char* argv[]) {    Target* tar = new Adapter();    tar->Request();    return 0;}
原创粉丝点击