Programming and Technology/Game Programming Patterns for Beginners/Singleton

International Game Developers Association

Jump to: navigation, search

NOT FINISHED YET

Table of contents

[edit] Introduction

The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

[edit] Implementation

[edit] In C++

Here is an example for an implementation in C++. The implementation for other languages doesn't differ much from this one, since it's called a pattern.

template<typename T>
class CSingleton {
    public:
        static T* getInstance() {
            // if the instance is not available...
            if(!_instance)
                // ...we create one
                _instance = new T;
            // and return it
            return _instance;
        }
        const void DeleteInstance() const {
            if(!_instance)
                return;
            delete _instance;
            _instance = 0;
        }

Finally, we make the constructors and the destructor private, so that they are not accessible from theoutside. This way, we prevent an external invoked instantiation of this class.

        private:
            // Constructor
            CSingleton() {;}
            // The copy constructor
            CSingleton(CSingleton& rhs) {;}
            // Destructor
            virtual ~CSingleton() {;}

            // The pointer to the running instance
            static T* _instance;
};

At the end, only thing left to do is to initialize our static members.

template<typename T>
T* CSingleton<T>::_instance = 0;

[edit] Multithreaded Implementation

[edit] The mutexclass

[edit] Links

[edit] Real-Life examples

Cynergy Engine [1] Singleton class in the Cynergy Engine [2]

[edit] Warning:

Singletons are often used in exchange for a global class or even a global pointer to the class, but this is not always a proper way to go about fixing your problem. Singletons remain in memory just as a global does, and can be accessed in the same way, making them improper for the same reasons. It is always best, if you are able, to utilize normal classes and pass around pointers to other functions when necessary.

Personal tools
Toolbox