设计模式--结构型

类适配器

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;
}
相关推荐
小鹏编程16 分钟前
【C++教程】C++中的基本数据类型
开发语言·c++·教程·少儿编程
熊峰峰17 分钟前
C++第十节:map和set的介绍与使用
开发语言·c++
Antonio91524 分钟前
【网络编程】事件选择模型
网络·c++
程序员Linc1 小时前
用OpenCV写个视频播放器可还行?(C++版)
c++·opencv·音视频·opencv 4.11
决斗小饼干1 小时前
并发编程知识总结
c++
Andlin2 小时前
《CMakeList 知识系统学习系列(三):函数和宏》
c++
Forget the Dream2 小时前
设计模式之迭代器模式
java·c++·设计模式·迭代器模式
周努力.2 小时前
设计模式之单例模式
单例模式·设计模式
大丈夫在世当日食一鲲2 小时前
Java中用到的设计模式
java·开发语言·设计模式
️Carrie️2 小时前
10.2 继承与多态
c++·多态·继承