C++实现服务容器及服务管理类

本文实现对单例服务的管理。

服务容器类实现功能:

  • 注册单例类型(默认构造函数);
  • 注册单例类型(接口及实现类,默认构造函数);
  • 注册单例类型(带自定义工厂函数);
  • 获取单例实例。

这些方法使用std::mutex加锁。

服务管理类实现功能:

  • 私有方法:注册单例类型、初始化服务、反初始化服务,
  • 共有方法:获取服务容器对象指针。

1. 服务容器类 (ContainerProvider.h)

#ifndef CONTAINERPROVIDER_H
#define CONTAINERPROVIDER_H

#include <unordered_map>
#include <typeindex>
#include <memory>
#include <functional>
#include <mutex>

class ContainerProvider
{
public:
    explicit ContainerProvider() {}

    //注册单例类型(默认构造函数)
    template<typename T>
    void RegisterSingleton()
    {
        std::lock_guard<std::mutex> locker(m_mutex);

        //存储类型的默认构造函数
        m_factoryMap[std::type_index(typeid(T))] = []() { return std::make_shared<T>(); };
    }

    //注册单例类型(接口及实现类,默认构造函数)
    template<typename TFrom, typename TTo>
    void RegisterSingleton()
    {
        std::lock_guard<std::mutex> locker(m_mutex);
        static_assert(std::is_base_of<TFrom, TTo>::value, "TTo must inherit from TFrom");

        //存储类型的默认构造函数
        m_factoryMap[std::type_index(typeid(TFrom))] = []() { return std::make_shared<TTo>(); };
    }

    //注册单例类型(带自定义工厂函数)
    template<class T>
    void RegisterSingleton(std::function<std::shared_ptr<T>()> factory)
    {
        std::lock_guard<std::mutex> locker(m_mutex);
        m_factoryMap[std::type_index(typeid(T))] = [factory]()
        {
            return std::static_pointer_cast<void>(factory());
        };
    }

    //获取单例实例(惰性初始化)
    template<class T>
    std::shared_ptr<T> Resolve()
    {
        //检查类型是否已注册
        auto typeIndex = std::type_index(typeid(T));
        auto factoryIt = m_factoryMap.find(typeIndex);
        if (factoryIt == m_factoryMap.end())
        {
            throw std::runtime_error("Type not registered: " + std::string(typeid(T).name()));
        }

        //检查实例是否已创建
        auto instanceIt = m_instanceMap.find(typeIndex);
        if (instanceIt == m_instanceMap.end())
        {
            //创建实例加锁
            std::lock_guard<std::mutex> locker(m_mutex);

            //创建实例并存储
            auto instance = factoryIt->second();
            m_instanceMap[typeIndex] = instance;
            return std::static_pointer_cast<T>(instance);
        }

        //返回现有实例
        return std::static_pointer_cast<T>(instanceIt->second);
    }

private:
    //存储类型构造函数的字典
    std::unordered_map<std::type_index, std::function<std::shared_ptr<void>()>> m_factoryMap;

    //存储单例实例的字典
    std::unordered_map<std::type_index, std::shared_ptr<void>> m_instanceMap;

    //线程安全锁
    std::mutex m_mutex;
};

#endif // CONTAINERPROVIDER_H

2. 服务管理类

2.1 服务管理类头文件 (ServiceManager.h)

#ifndef SERVICEMANAGER_H
#define SERVICEMANAGER_H

#include "ContainerProvider.h"

class ServiceManager
{
public:
    ~ServiceManager();
    static ServiceManager& instance();

    void startup();
    void shutdowm();

    std::shared_ptr<ContainerProvider> getContainer() const { return m_container; }

private:
    ServiceManager();

    void registerTypes();
    void initServices();
    void unInitServices();

private:
    std::shared_ptr<ContainerProvider> m_container;
};

#endif // SERVICEMANAGER_H

2.2 服务管理类实现 (ServiceManager.cpp)

#include "ServiceManager.h"
#include "LogService.h"
#include "XmlConfigService.h"

ServiceManager::ServiceManager()
    : m_container(std::make_shared<ContainerProvider>())
{
    registerTypes();
}

ServiceManager::~ServiceManager()
{

}

ServiceManager& ServiceManager::instance()
{
    static ServiceManager instance;
    return instance;
}

void ServiceManager::startup()
{
    initServices();
}

void ServiceManager::shutdowm()
{
    unInitServices();
}

/// <summary>
/// 注册服务
/// </summary>
void ServiceManager::registerTypes()
{
    //注册单例服务
    m_container->RegisterSingleton<LogService>();
    m_container->RegisterSingleton<XmlConfigService>();
}

void ServiceManager::initServices()
{
    auto logService = m_container->Resolve<LogService>();
    logService->startup();

    auto configService = m_container->Resolve<XmlConfigService>();
    configService->loadConfig();
}

void ServiceManager::unInitServices()
{
    auto logService = m_container->Resolve<LogService>();
    logService->shutdown();
}

3. 服务管理类应用

3.1 主窗口头文件 (mainwindow.h)

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "LogService.h"

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    LogService *m_logService;
};
#endif // MAINWINDOW_H

3.2 主窗口实现 (mainwindow.cpp)

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    m_logService = new LogService();
    m_logService->startup();
}

MainWindow::~MainWindow()
{
    m_logService->shutdown();
    delete m_logService;
}
posted @ 2025-07-07 10:45  xhubobo  阅读(7)  评论(0)    收藏  举报