设计模式--结构型

类适配器

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;
}
相关推荐
CSDN_RTKLIB14 小时前
【GNU、GCC、g++、MinGW、MSVC】上
c++·gnu
b***748814 小时前
C++在系统中的内存对齐
开发语言·c++
散峰而望14 小时前
C++数组(三)(算法竞赛)
开发语言·c++·算法·github
4***149014 小时前
C++在系统中的编译优化
开发语言·c++
mit6.82414 小时前
[HomeKey] 握手协议 | NFC协议处理器
c++
oioihoii14 小时前
C++程序执行起点不是main:颠覆你认知的真相
开发语言·c++
hetao173383714 小时前
2025-11-25~26 hetao1733837的刷题记录
c++·算法
u***u68515 小时前
C++在系统中的异常处理
java·开发语言·c++
4***R24015 小时前
C++在音视频处理中的库
开发语言·c++·音视频
周一上线16 小时前
EDA 中的 DRC检测——并查集优化mincut规则检测
c++·eda·经验·工艺