设计模式--结构型

类适配器

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;
}
相关推荐
玖剹1 分钟前
记忆化搜索题目(二)
c语言·c++·算法·leetcode·深度优先·剪枝·深度优先遍历
陳10303 分钟前
C++:string(3)
开发语言·c++
搬砖的kk33 分钟前
Lycium++ - OpenHarmony PC C/C++ 增强编译框架
c语言·开发语言·c++
胖咕噜的稞达鸭2 小时前
算法日记专题:位运算II( 只出现一次的数字I II III 面试题:消失的两个数字 比特位计数)
c++·算法·动态规划
茉莉玫瑰花茶2 小时前
ProtoBuf - 3
服务器·c++·protobuf
Algebraaaaa2 小时前
为什么线程阻塞要用.join而不是.wait
java·c++·python
墨雪不会编程2 小时前
C++内存管理深度剖析
java·开发语言·c++
万法若空2 小时前
【wxWidgets教程】控件基础知识
c++·gui·wxwidgets·事件处理
图形学爱好者_Wu2 小时前
每日一个C++知识点|模板
c++
xiaolang_8616_wjl3 小时前
c++超级细致的基本框架
开发语言·数据结构·c++·算法