设计模式--结构型

类适配器

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;
}
相关推荐
JMchen12317 分钟前
Android NDK开发从入门到实战:解锁应用性能的终极武器
android·开发语言·c++·python·c#·android studio·ndk开发
花间相见30 分钟前
【Java基础面试题】—— 核心知识点面试题(含答案):语法+集合+JVM+设计模式+算法
java·jvm·设计模式
程序猿编码1 小时前
隐匿注入型ELF加壳器:原理、设计与实现深度解析(C/C++ 代码实现)
c语言·网络·c++·elf·代码注入
m0_734998012 小时前
Day 26
数据结构·c++·算法
Summer_Uncle3 小时前
【QT学习】Qt界面布局的生命周期和加载时机
c++·qt
朱一头zcy3 小时前
设计模式入门:最简单的模板方法模式
笔记·设计模式·模板方法模式
小CC吃豆子3 小时前
C++ 继承
开发语言·c++
tankeven3 小时前
HJ151 模意义下最大子序列和(Easy Version)
c++·算法
fengenrong3 小时前
20260325
开发语言·c++
BestOrNothing_20153 小时前
从C++结构体、类到 PID 控制器:运动控制初学者如何理解 C++ 工程代码
c++·面向对象·pid·运动控制·.h与.cpp·struct与class