设计模式--结构型

类适配器

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;
}
相关推荐
喝拿铁写前端8 小时前
从面条代码到抽象能力:一个小表单场景里的前端成长四阶段
前端·设计模式·架构
依米_8 小时前
一文带你剖析 Promise.then all 实现原理,状态机、发布订阅模式完美实现异步编程
javascript·设计模式
jzhwolp9 小时前
从基本链表到侵入式链表,体会内核设计思路
c语言·后端·设计模式
爱凤的小光10 小时前
图漾GM461-E1相机专栏
c++
qwepoilkjasd11 小时前
C++智能指针介绍
c++
·白小白11 小时前
力扣(LeetCode) ——43.字符串相乘(C++)
c++·leetcode
咬_咬11 小时前
C++仿muduo库高并发服务器项目:Poller模块
服务器·开发语言·c++·epoll·muduo
FMRbpm12 小时前
链表5--------删除
数据结构·c++·算法·链表·新手入门
Kimser12 小时前
QT C++ QWebEngine与Web JS之间通信
javascript·c++·qt
QT 小鲜肉12 小时前
【QT/C++】Qt样式设置之CSS知识(系统性概括)
linux·开发语言·css·c++·笔记·qt