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

24 篇文章 0 订阅
24 篇文章 3 订阅
目录:

设计模式学习笔记首页
设计模式(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 once

class 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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值