Singleton in C
In C , there are several ways to implement the Singleton design pattern, a technique that ensures a class has only a single instance. Following are two common approaches to creating a Singleton class:
The Classic Singleton with a Pointer Return
In this method, the Singleton class returns a pointer to its instance:
<code class="cpp">class A { private: static A* m_pA; A(); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); };</code>
However, this approach has a potential issue if the FreeInstance() method is called while the object still has references. To address this, avoid manually freeing Singleton objects.
Singleton with a Reference Return
Returning the Singleton as a reference is another approach that offers better safety:
<code class="cpp">class A { private: static A* m_pA; explicit A(); void A(const A& a); void A(A &a); const A& operator=(const A& a); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); };</code>
This implementation ensures that you can't accidentally destroy the Singleton object.
Additional Considerations
For further reading and best practices on Singleton design, refer to the suggested resources:
The above is the detailed content of How to Implement the Singleton Design Pattern in C ?. For more information, please follow other related articles on the PHP Chinese website!