设计模式--结构型

类适配器

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 分钟前
设计模式——备忘录设计模式(行为型)
设计模式
庄小焱10 分钟前
设计模式——代理设计模式(结构型)
设计模式
@蓝莓果粒茶12 分钟前
LeetCode第245题_最短单词距离III
c语言·c++·笔记·学习·算法·leetcode·c#
哆啦A梦的口袋呀43 分钟前
基于Python学习《Head First设计模式》第三章 装饰者模式
python·学习·设计模式
哆啦A梦的口袋呀44 分钟前
基于Python学习《Head First设计模式》第五章 单件模式
python·学习·设计模式
showmeyourcode0.o1 小时前
QT常用控件(1)
开发语言·c++·qt
小黄人软件1 小时前
C++ Visual Studio 2017厂商给的源码没有.sln文件 易兆微芯片下载工具加开机动画下载。
开发语言·c++·visual studio
季鸢1 小时前
Java设计模式之备忘录模式详解
java·设计模式·备忘录模式
AI迅剑2 小时前
模块二:C++核心能力进阶(5篇)篇二:《多线程编程:C++线程池与原子操作实战》(14万字深度指南)
java·开发语言·c++
oioihoii2 小时前
C++中锁与原子操作的区别及取舍策略
java·开发语言·c++