Adapter Pattern(适配器模式)

来源:互联网 发布:android 读取蓝牙数据 编辑:程序博客网 时间:2024/06/05 01:50

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 = StackAdaptee_two = QueueOperationA = 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 operationAAdapter operationCAdapter operationBAdapter operationD

5.生活中的实例应用

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

6.适用场景

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

0 0
原创粉丝点击