设计模式--结构型

类适配器

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;
}
相关推荐
铛铛啦啦啦27 分钟前
“对象创建”模式之原型模式
设计模式·原型模式
2301_803554521 小时前
c++中的绑定器
开发语言·c++·算法
海棠蚀omo1 小时前
C++笔记-位图和布隆过滤器
开发语言·c++·笔记
消失的旧时光-19432 小时前
c++ 的标准库 --- std::
c++·jni
GiraKoo2 小时前
【GiraKoo】C++11的新特性
c++·后端
不午睡的探索者2 小时前
告别性能瓶颈!Python 量化工程师,进击 C++ 高性能量化交易的“必修课”!
c++·github
OpenC++2 小时前
【C++】观察者模式
c++·观察者模式·设计模式
老歌老听老掉牙2 小时前
粒子群优化算法实现与多维函数优化应用
c++·pso·粒子群算法
myloveasuka2 小时前
信号操作集函数
linux·运维·服务器·c语言·c++·vscode
山野万里__3 小时前
C++与Java内存共享技术:跨平台与跨语言实现指南
android·java·c++·笔记