C++设计模式PIMPL模式

Pimpl是"Pointer to implementation"的缩写,它是一种常用的C++设计模式。这种模式的核心思想是将类的实现细节从其接口中分离出来。想象一下,我们生活的世界中充满了这种分离:我们不需要知道电视是如何工作的,只需要知道如何使用遥控器。同样地,Pimpl模式允许我们仅展示类的功能,而隐藏其内部工作方式

在C++中,头文件依赖是一个普遍的问题。当一个头文件改变时,所有包含这个头文件的源文件都需要重新编译。这可能导致编译时间显著增加,特别是在大型项目中。

考虑一个类,它包含了许多私有数据成员和复杂的实现。如果我们把所有这些都放在头文件中,那么任何小小的修改都会触发大量的重新编译。

Pimpl模式通过将实现细节移到源文件中,避免了这个问题,从而使得头文件变得轻量级和稳定。

cpp 复制代码
//DeviceManager类
class DeviceManager {
public:
    DeviceManager() : d_pointer(std::make_unique<DeviceManagerPrivate>(*this)) {}

    void handleDeviceEvent(const std::string& event) {
        // 处理设备事件
        std::cout<<"event:"<<event<<"\n";
    }

    void log(const std::string& message) {
        // 记录日志
        std::cout<<"write to file"<<"\n";
    }

private:
    std::unique_ptr<DeviceManagerPrivate> d_pointer;
};

//DEviceManagerPrivate类
class DeviceManagerPrivate {
public:
    DeviceManagerPrivate(DeviceManager& p_instance)
        : _p_instance(p_instance) {}

    void insertDevice(std::shared_ptr<Device> device) {
        std::lock_guard<std::mutex> lock(_device_map_mutex);
        _device_map[device->getId()] = device;
        _p_instance.handleDeviceEvent("Device inserted"); // 调用DeviceManager的方法
    }

    void removeDevice(uint32_t id) {
        std::lock_guard<std::mutex> lock(_device_map_mutex);
        _device_map.erase(id);
        _p_instance.handleDeviceEvent("Device removed"); // 调用DeviceManager的方法
    }

private:
    DeviceManager& _p_instance;
    std::mutex _device_map_mutex;
    std::map<uint32_t, std::shared_ptr<Device>> _device_map;
};
相关推荐
blasit18 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
七月丶1 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞1 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼1 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟2 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder2 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
阿星AI工作室2 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦3 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding