设计模式--结构型

类适配器

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;
}
相关推荐
是2的10次方啊1 小时前
🏗️ 结构型设计模式:代码架构的魔法师
设计模式
哈基米喜欢哈哈哈2 小时前
设计模式(一)——抽象工厂模式
设计模式·抽象工厂模式
打点计时器2 小时前
Onnx模型部署到Arm64进行推理
c++
Yang-Never2 小时前
设计模式 -> 策略模式(Strategy Pattern)
android·开发语言·设计模式·kotlin·android studio·策略模式
ikkkkkkkl2 小时前
LeetCode:209.长度最小的子数组&&3.无重复字符的最长子串
数据结构·c++·算法·leetcode
pointers_syc2 小时前
【设计模式】4.装饰器模式
设计模式·装饰器模式
非科班CPP程序员2 小时前
新手BUG:函数中 static 变量的赋值语句只会执行一次
数据结构·c++·算法
用户6120414922133 小时前
C语言做的科学转换计算器
c语言·c++·后端
程序员编程指南7 小时前
Qt 嵌入式 Linux 系统定制全指南
linux·c语言·开发语言·c++·qt
R-G-B12 小时前
【08】C++实战篇——C++ 生成动态库.dll 及 C++调用DLL,及实际项目中的使用技巧
c++·c++ 生成动态库.dll·c++ 生成静态库.lib·c++调用动态库.dll·c++调用静态库.lib·c++调用dll·c++调用lib