设计模式--结构型

类适配器

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;
}
相关推荐
请揣满RMB1 小时前
Qt常用控件——QRadioButton和QCheckBox
开发语言·c++·qt
吴天德少侠4 小时前
c++返回一个pair类型
开发语言·c++
ok!ko4 小时前
设计模式之工厂模式(通俗易懂--代码辅助理解【Java版】)
java·开发语言·设计模式
AI让世界更懂你6 小时前
漫谈设计模式 [18]:策略模式
python·设计模式·策略模式
Pandaconda6 小时前
【C++ 面试 - 新特性】每日 3 题(六)
开发语言·c++·经验分享·笔记·后端·面试·职场和发展
北南京海7 小时前
【C++入门(5)】类和对象(初始类、默认成员函数)
开发语言·数据结构·c++
Yusei_05237 小时前
C++基础知识6 vector
开发语言·c++
黄卷青灯777 小时前
c++ 定义类 介绍
开发语言·c++·定义类
伍心7 小时前
004: VTK读入数据---vtkImageData详细说明
c++·windows·microsoft·mfc·软件工程·visual studio
bbqz0077 小时前
逆向WeChat(六)
c++·微信·小程序·逆向·mojo·嗅探·抓包https·devtool·sniff