Adapter Pattern(适配器模式)

1.定义

适配器模式:
将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper), 可以作为类结构型模式,也可以作为对象结构型模式.

2.结构

(1)Target(目标抽象类): 目标抽象类定义客户所需接口,可以是一个抽象类或接口,也可以是具体类
(2)Adapter(适配器类): 适配器可以调用另一个接口,作为一个转换器,对Adapter和Target进行适配.适配器类是适配器模式的核心, 在对象适配器模式中,它通过Target并关联一个Adaptee对象使二者产生联系
(3)Adaptee(适配者类): 适配者即并被适配的角色,它定义了一个已经存在的接口,这个接口需要适配,适配者类一般是一个具体类,包含了客户希望使用的业务方法,在某些情况下可能没有适配者类的源代码

3.Product.h

#include<iostream>
#include<string>
using namespace std;

class Adapter {
public:
    void operationA(int x) {
        cout << "Adapter operationA" << endl;
    }
    void operationB(int x) {
        cout << "Adapter operationB" << endl;
    }
    void operationC() {
        cout << "Adapter operationC" << endl;
    }
    void operationD() {
        cout << "Adapter operationD" << endl;
    }
};
// 目标接口
class Target {
public:
    virtual void Operation(int x) = 0;
    virtual void anotherOperation() = 0;
};
class Adaptee_one : public Target {
private:
    Adapter adapter;
public:
    void Operation(int x) {
        adapter.operationA(x);
    }
    void anotherOperation() {
        adapter.operationC();
    }
};
class Adaptee_two : public Target {
private:
    Adapter adapter;
public:
    void Operation(int x) {
        adapter.operationB(x);
    }
    void anotherOperation() {
        adapter.operationD();
    }
};
/*
It will be easier to understand if:
Adaptee = Deque;
Target = Sequence;
Adaptee_one = Stack
Adaptee_two = Queue
OperationA = push_back;
OperationB = push_front;
OperationC = pop_back;
OperationD = pop_front;
Operation = push;
anotherOperation = pop;
*/

4.main.cpp

#include"Product.h"
int main() {
    Target* tg1 = new Adaptee_one;
    Target* tg2 = new Adaptee_two;
    tg1->Operation(1);
    tg1->anotherOperation();
    tg2->Operation(2);
    tg2->anotherOperation();
    delete tg1;
    delete tg2;
    return 0;
}

输出结果:

Adapter operationA
Adapter operationC
Adapter operationB
Adapter operationD

5.生活中的实例应用

有的笔记本电脑的工作电压是20V,但是我国的家庭用电是200V,要让20V的笔记本电脑能够在220V的电压下工作,就需要一个电源适配器也就是充电器/变压器.

6.适用场景

(1)系统需要使用一些现有的代码,而这些类的接口(例如方法名)不符合系统的需要,甚至没有这些类的源代码
(2)想创建一个可以重复使用的类,用于与一些彼此之间没有太大联系的类,包括一些可能在将来引进的类一起工作.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值