• Adapter 适配器模式


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

    • 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
    • 需要适配的类(Adaptee):需要适配的类或适配者类。
    • 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。  

    有类适配器与对象适配器两种类型。

    下列情况使用适配器模式:

    • 要使用的类的接口不符合需求。
    • 建立一个可复用的类,可以与不相关的类或不可预见的类协同工作。
    • 要使用一些已存在的子类,直接适配它的父类接口。


     1 #include <cstdio>
     2 
     3 class Adaptee {
     4 public:
     5     void SpecificRequest(int cost) {
     6         printf("such adaptee so %d
    ", cost);
     7     }
     8 
     9 };
    10 
    11 class Target {
    12 public:
    13     virtual void Request() = 0;
    14 };
    15 
    16 class AdapterCls : public Target, private Adaptee {
    17 public:
    18     void Request() {
    19         SpecificRequest(100);
    20     }
    21 };
    22 
    23 class AdapterImp : public Target {
    24 private:
    25     Adaptee adaptee;
    26 public:
    27     void Request() {
    28         adaptee.SpecificRequest(100);
    29     }
    30 };
    31 
    32 class Client
    33 {
    34 public:
    35     Client();
    36     ~Client();
    37     void gaoCls() {
    38         Target *p = new AdapterCls();
    39         p->Request();
    40         delete p;
    41     }
    42     void gaoImp() {
    43         Target *p = new AdapterImp();
    44         p->Request();
    45         delete p;
    46     }
    47 private:
    48 };
    49 
    50 Client::Client()
    51 {
    52 }
    53 
    54 Client::~Client()
    55 {
    56 }
  • 相关阅读:
    第七章 过滤器 Filter(二)
    第七章 过滤器基础 Filter
    学了近一个月的java web 感想
    js写的一个简单的手风琴菜单
    第六章 对象作用域与servlet事件监听器
    第五章 Web应用程序状态管理
    第四章 使用Servlet处理HTTP请求
    第三章 使用Servlet处理HTTP响应
    第二章 Servlet基础
    myeclipse解决Fail to create the java Virtual Machine
  • 原文地址:https://www.cnblogs.com/zinthos/p/3963330.html
Copyright © 2020-2023  润新知