zoukankan      html  css  js  c++  java
  • 设计模式14——适配器模式

    适配器模式可以使接口不相同的几个对象通过适配来统一接口。Target与Adaptee各自拥有自己的方法,但接口不同,可以通过Adapter进行统一。

     1 #ifndef Adapter_H_H
     2 #define Adapter_H_H
     3 
     4 #include <iostream>
     5 using namespace std;
     6 
     7 class Target
     8 {
     9 public:
    10     virtual void display() { cout << "This is a common target!" << endl; }
    11     virtual ~Target() {}
    12 };
    13 
    14 class Adaptee
    15 {
    16 public:
    17     void specialDisplay() { cout << "This is a special target!" << endl; }
    18 };
    19 
    20 class Adapter : public Target
    21 {
    22 public:
    23     Adapter() : adaptee(new Adaptee()) {}
    24     virtual void display() { adaptee->specialDisplay(); }
    25     ~Adapter() { delete adaptee; }
    26 
    27 private:
    28     Adaptee *adaptee;
    29 };
    30 
    31 
    32 void AdapterTest()
    33 {
    34     Target *target1 = new Target();
    35     Target *target2 = new Adapter();
    36 
    37     target1->display();
    38     target2->display();
    39 
    40     delete target1;
    41     delete target2;
    42 }
    43 
    44 
    45 #endif

    运行结果:

    Adaptee与Target接口不同,却可以通过Adapter进行统一。

  • 相关阅读:
    3553: [Shoi2014]三叉神经树(树链剖分)
    Hive学习笔记(三)-- DML和DDL操作
    Hive学习笔记(二)
    Hive学习笔记(一)
    Hive安装步骤
    【Netty】NIO框架Netty入门
    【Netty】Netty入门之WebSocket小例子
    记录一次面试
    线程池面试
    反射面试
  • 原文地址:https://www.cnblogs.com/MiniHouse/p/3984528.html
Copyright © 2011-2022 走看看