zoukankan      html  css  js  c++  java
  • 7 结构型模式-----适配器模式

    模式动机:有时软件复用的一个难题就是接口的不兼容性,适配器的职责就是为客户提供兼容的适配者接口,使得客户只需访问一类接口就可以调用合适的适配者,而其中的适配细节则有适配器来完成。

    模式定义(Adapter Pattern)将一个接口转换为用户期望的接口,使得那些接口不兼容的类可以一起工作。

    模式结构图:

     

    模式代码:

    bt_适配器模式.h

     1 #ifndef AP_H
     2 #define AP_H
     3 #include <iostream>
     4 
     5 using namespace std;
     6 
     7 /*
     8     定义抽象目标类
     9 */
    10 class Target
    11 {
    12 public:
    13     virtual ~Target(){ }
    14     virtual void request() = 0;
    15 };
    16 
    17 /*
    18     适配者类
    19 */
    20 class Adaptee
    21 {
    22 public:
    23     void specificRequest()
    24     {
    25         cout << "成功调用适配者方法" << endl;
    26     }
    27 };
    28 
    29 /*
    30     适配器类
    31 */
    32 class Adapter : public Target
    33 {
    34 public:
    35     virtual void request()
    36     {
    37         pa->specificRequest();
    38     }
    39 
    40 private:
    41     Adaptee* pa;    // 指向合适的适配者
    42 };
    43 
    44 #endif // AP_H

    测试用例.cpp

     1 #include "bt_适配器模式.h"
     2 
     3 int main()
     4 {
     5     cout << "***** 适配器模式测试 *****" << endl;
     6     Target* target = new Adapter;   // 实例化一个与目标关联的适配器
     7     target->request();                // 客户端调用
     8 
     9     delete target;
    10 
    11     return 0;
    12 }
    
    

    模式分析:该模式将目标类和具体适配者类解耦,增加了系统的灵活性和可扩展性,更换适配器时比较方便,不需要修改已有类,符合“开闭原则”。但是若需要更换一个已有的Adaptee方法比较麻烦,需要借助Adaptee的子类才能完成。同时如果想让一个Adapter与多个Adaptee(Adaptee及其子类)同时工作,也必须生成Adaptee的子类,并且需要在Adapter类中调用Adaptee子类的方法。

     

     

  • 相关阅读:
    pipelinewise 学习二 创建一个简单的pipeline
    pipelinewise 学习一 docker方式安装
    Supercharging your ETL with Airflow and Singer
    ubuntu中使用 alien安装rpm包
    PipelineWise illustrates the power of Singer
    pipelinewise 基于singer 指南的的数据pipeline 工具
    关于singer elt 的几篇很不错的文章
    npkill 一个方便的npm 包清理工具
    kuma docker-compose 环境试用
    kuma 学习四 策略
  • 原文地址:https://www.cnblogs.com/benxintuzi/p/4545065.html
Copyright © 2011-2022 走看看