设计模式--结构型

类适配器

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 小时前
从`std::mutex`到`std::lock_guard`与`std::unique_lock`的演进之路
开发语言·c++
卡提西亚2 小时前
C++笔记-10-循环语句
c++·笔记·算法
亮剑20183 小时前
第1节:C语言初体验——环境、结构与基本数据类型
c++
William_wL_3 小时前
【C++】类和对象(下)
c++
William_wL_4 小时前
【C++】内存管理
c++
星星火柴9364 小时前
笔记 | C++面向对象高级开发
开发语言·c++·笔记·学习
悲伤小伞5 小时前
Linux_Socket_UDP
linux·服务器·网络·c++·网络协议·udp
八个程序员5 小时前
自定义函数(C++)
开发语言·c++·算法
乐悠小码6 小时前
Java设计模式精讲---02抽象工厂模式
java·设计模式·抽象工厂模式
微露清风7 小时前
系统性学习C++-第十讲-stack 和 quene
java·c++·学习