设计模式--结构型

类适配器

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;
}
相关推荐
天堂的恶魔94615 分钟前
C++项目 —— 基于多设计模式下的同步&异步日志系统(4)(双缓冲区异步任务处理器(AsyncLooper)设计)
开发语言·c++·设计模式
Zhuai-行淮1 小时前
施磊老师基于muduo网络库的集群聊天服务器(二)
开发语言·网络·c++
ChoSeitaku1 小时前
NO.97十六届蓝桥杯备战|数论板块-最大公约数和最小公倍数|欧几里得算法|秦九韶算法|小红的gcd(C++)
c++·算法·蓝桥杯
侧耳倾听1111 小时前
java 设计模式之单例模式
java·单例模式·设计模式
周Echo周2 小时前
8、constexpr if、inline、类模版参数推导、lambda的this捕获---c++17
linux·开发语言·c++·算法·vim
逐光沧海2 小时前
函数对象-C++
开发语言·c++·算法
天堂的恶魔9462 小时前
C++项目 —— 基于多设计模式下的同步&异步日志系统(5)(单例模式)
c++·单例模式·设计模式
yatingliu20192 小时前
牛客 | OJ在线编程常见输入输出练习
数据结构·c++·算法
火热的茶独独3 小时前
C语言==》字符串断行
c语言·c++
炯哈哈3 小时前
【上位机——MFC】MFC入门
开发语言·c++·mfc·上位机