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;
};
相关推荐
归寻太乙13 分钟前
C++函数重载完成日期类相关计算
开发语言·c++
尽蝶叙15 分钟前
C++:分苹果【排列组合】
开发语言·c++·算法
憧憬成为原神糕手41 分钟前
c++_list
开发语言·c++
zyh2005043042 分钟前
c++的decltype关键字
c++·decltype
2401_862886781 小时前
蓝禾,汤臣倍健,三七互娱,得物,顺丰,快手,游卡,oppo,康冠科技,途游游戏,埃科光电25秋招内推
前端·c++·python·算法·游戏
徐霞客3202 小时前
对于C++继承中子类与父类对象同时定义其析构顺序的探究
开发语言·c++
敲上瘾2 小时前
多态的使用和原理(c++详解)
开发语言·数据结构·c++·单片机·aigc·多态·模拟
心怀花木2 小时前
【C++】list容器的基本使用
c++·stl·list
我命由我123452 小时前
GPIO 理解(基本功能、模拟案例)
linux·运维·服务器·c语言·c++·嵌入式硬件·c#
weixin_515033933 小时前
ccfcsp-202006(4、5)
c++·算法