Home > Backend Development > C++ > How to Implement the Singleton Design Pattern in C ?

How to Implement the Singleton Design Pattern in C ?

DDD
Release: 2024-11-03 17:57:02
Original
346 people have browsed it

How to Implement the Singleton Design Pattern in C  ?

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>
Copy after login

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>
Copy after login

This implementation ensures that you can't accidentally destroy the Singleton object.

Additional Considerations

  • Make the constructor private to prevent direct object creation.
  • Override the default copy constructor and assignment operator to prevent copying.
  • Use a static method to access the Singleton instance, guaranteeing its creation and destruction only once.

For further reading and best practices on Singleton design, refer to the suggested resources:

  • [Singleton: How Should It Be Used](https://refactoring.guru/design-patterns/singleton)
  • [C Singleton Design Pattern](https://www.learncpp.com/cpp-tutorial/singleton-design-pattern/)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template