Singleton Pattern in C++

In programming, we sometimes use the singleton pattern:It aims to ensure that a class has only one instance and provides a global access point to that instance. This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created.Common applications of the singleton pattern include: task managers, where there can only be one instance globally. To facilitate the implementation of the singleton pattern and avoid rewriting code for each singleton class, we encapsulate the singleton class, allowing you to simply inherit from this class and define a singleton macro. The implementation and usage code are as follows:

Singleton Pattern Class Singleton.h:

#pragma once
#define SINGLETON_BODY(T) static T *GetSingletonPtr() { return m_singleton; } static T &GetSingleton() { return (*m_singleton); }#define SINGLETON_END(T) template<> T* Singleton<T>::m_singleton = 0;
namespace xm{    template <typename T> class Singleton    {    public:        Singleton()        {            m_singleton = static_cast<T *>(this);        }        ~Singleton()        {            m_singleton = 0;        }
        static Singleton &GetSingleton()        {            return (*m_singleton);        }
        static Singleton *GetSingletonPtr() { return m_singleton; }
    private:        Singleton(const Singleton<T> &);        Singleton &operator=(const Singleton<T> &);
    public:        static T *m_singleton;    };}

Singleton Test Class UDPClient.h:

#pragma once
#include "Core/Singleton.h"
namespace xm{    class UDPClient : public Singleton<UDPClient> // Inherit singleton pattern    {    public:        UDPClient() {}        ~UDPClient() {}
        SINGLETON_BODY(UDPClient) // Define singleton function
    public:        int m_test = 0;    };    SINGLETON_END(UDPClient) // Define end of singleton}

Test Code main.cpp:

#include "UDPClient.h"
#include <iostream>
int main() {    xm::UDPClient u;    u.m_test = 1;    std::cout << u.m_test << std::endl;    std::cout << xm::UDPClient::GetSingleton().m_test << std::endl;
    xm::UDPClient::GetSingleton().m_test = 3;    std::cout << u.m_test << std::endl;    std::cout << xm::UDPClient::GetSingleton().m_test << std::endl;    return 0;}

Running Result:

Singleton Pattern in C++

Leave a Comment