设计模式--结构型

类适配器

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;
}
相关推荐
曙曙学编程3 分钟前
stm32——独立看门狗,RTC
c语言·c++·stm32·单片机·嵌入式硬件
励志不掉头发的内向程序员10 分钟前
C++进阶——多态
开发语言·c++·学习
楼田莉子1 小时前
C++算法专题学习:栈相关的算法
开发语言·c++·算法·leetcode
dragoooon341 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法
Suresoft China1 小时前
软件测试|STATIC 代码静态验证工具 C/C++ 工具链设置指南
c++·单元测试·静态测试·测试覆盖率·static·代码覆盖率·工具链设置
kyle~2 小时前
排序---冒泡排序(Bubble Sort)
c语言·c++·算法
hmcjn(小何同学)2 小时前
轻松Linux-9.进程间通信
linux·运维·服务器·c++·bash
o0向阳而生0o2 小时前
100、23种设计模式之适配器模式(9/23)
设计模式·适配器模式
落羽的落羽2 小时前
【C++】C++11的包装器:function与bind简介
c++·学习
打不了嗝 ᥬ᭄2 小时前
【Linux】线程概念与控制
linux·c++