设计模式--结构型

类适配器

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;
}
相关推荐
小王子10243 分钟前
设计模式Python版 组合模式
python·设计模式·组合模式
我不是代码教父5 分钟前
[原创](Modern C++)现代C++的关键性概念: 流格式化
c++·字符串格式化·流格式化·cout格式化
利刃大大22 分钟前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
子燕若水41 分钟前
mac 手工安装OpenSSL 3.4.0
c++
*TQK*1 小时前
ZZNUOJ(C/C++)基础练习1041——1050(详解版)
c语言·c++·编程知识点
ElseWhereR1 小时前
C++ 写一个简单的加减法计算器
开发语言·c++·算法
*TQK*2 小时前
ZZNUOJ(C/C++)基础练习1031——1040(详解版)
c语言·c++·编程知识点
linwq82 小时前
设计模式学习(二)
java·学习·设计模式
※DX3906※2 小时前
cpp实战项目—string类的模拟实现
开发语言·c++
萌の鱼3 小时前
leetcode 2080. 区间内查询数字的频率
数据结构·c++·算法·leetcode