设计模式--结构型

类适配器

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;
}
相关推荐
疯狂的喵5 小时前
C++编译期多态实现
开发语言·c++·算法
2301_765703145 小时前
C++中的协程编程
开发语言·c++·算法
m0_748708055 小时前
实时数据压缩库
开发语言·c++·算法
小魏每天都学习5 小时前
【算法——c/c++]
c语言·c++·算法
m0_748233176 小时前
30秒掌握C++核心精髓
开发语言·c++
风清扬_jd7 小时前
libtorrent-rasterbar-2.0.11编译说明
c++·windows·p2p
u0109272717 小时前
C++中的RAII技术深入
开发语言·c++·算法
彷徨而立8 小时前
【C/C++】strerror、GetLastError 和 errno 的含义和区别?
c语言·c++
琹箐8 小时前
设计模式——观察者模式
观察者模式·设计模式
誰能久伴不乏8 小时前
【Qt实战】工业级多线程串口通信:从底层协议设计到完美收发闭环
linux·c++·qt