设计模式--结构型

类适配器

c 复制代码
#include <queue>
#include <iostream>
#include <algorithm>
#include <iterator>

using namespace std;

// 目标接口
class Target
{
  public:
    virtual ~Target() {}
    virtual void method() = 0;
};

// 适配者类
class Adaptee
{
  public:
    void spec_method()
    {
        std::cout << "spec_method run" << std::endl;
    }
};

// 类适配器
class Adapter : public Target, public Adaptee
{
  public:
    void method() override
    {
        std::cout << "call from Adapter: " << std::endl;
        spec_method();
    }
};

int main(int argc, char** argv)
{
    Adaptee adaptee;
    adaptee.spec_method();
    
    std::cout << std::endl;

    Adapter adapter;
    adapter.method();

    return 0;
}

对象适配器

c 复制代码
#include <queue>
#include <iostream>
#include <algorithm>
#include <iterator>

using namespace std;

// 目标接口
class Target
{
  public:
    virtual ~Target() {}
    virtual void method() = 0;
};

// 适配者类
class Adaptee
{
  public:
    void spec_method()
    {
        std::cout << "spec_method run" << std::endl;
    }
};

// 类适配器
class Adapter : public Target
{
  public:
    Adapter(Adaptee* adaptee)
        : adaptee_{adaptee}
    {
    }

    void method() override
    {
        std::cout << "call from Adapter: " << std::endl;
        adaptee_->spec_method();
    }

  private:
    Adaptee* adaptee_;
};

int main(int argc, char** argv)
{
    Adaptee adaptee;
    adaptee.spec_method();

    std::cout << std::endl;

    Adapter adapter(&adaptee);
    adapter.method();

    return 0;
}
相关推荐
fufu03111 小时前
vscode配置C/C++环境,用GDB调试简单程序分享
开发语言·c++
nnsix1 小时前
设计模式 - 模板方法模式 笔记
笔记·设计模式·模板方法模式
水云桐程序员2 小时前
C++变量的概念及用法
开发语言·c++
水饺编程3 小时前
第5章,[Win32 章节] :几种典型的颜色
c语言·c++·windows·visual studio
Larry_Yanan3 小时前
QML面试常见问题(一)QML中组件呈现方式的方法有哪些
开发语言·c++·qt·ui·面试
杨校3 小时前
杨校老师课堂之C++的位运算应用专项训练
开发语言·c++
j7~4 小时前
【MYSQL】在Centos7和ubuntu22.04环境下安装
数据库·c++·mysql·ubuntu·centos
代码中介商4 小时前
C++ STL 容器完全指南(三):deque、list 与 map 深度详解
开发语言·c++
eggrall4 小时前
Linux进程信号——像收快递一样理解 Linux 信号
linux·开发语言·c++
‎ദ്ദിᵔ.˛.ᵔ₎4 小时前
c++ 11左值和右值
c++