What is singleton set

The singleton pattern describes a class that can only be instantiated once, but whose only instance can be accessed globally.

The singleton pattern thus represents a kind of improved global variable.

The singleton pattern can always be used when unique objects are to be modeled for an application. In a game, for example, there should only ever be exactly one world. The printers in a system must be managed by exactly one printer manager. There are many examples of such unique objects. Their uniqueness is guaranteed by the type described by the singleton pattern. This instantiates itself, but does not offer others the opportunity to create further instances.

Here is an example:

In the example, the header file and the actual class definition were again omitted because it is easier to understand.

With "static bool instanceFlag;" we store a boolean value which, if true, means that this class has already been instantiated. If this is the case, "static Singleton * getInstance ();" simply "static Singleton * single;" given back. If not, a new instance of the class is simply saved in single, instanceFlag is set to true and single is returned.

The main () function calls first "Singleton * sc1 = Singleton :: getInstance ();" on. Since there is no instance of the class yet, it is created. Then we call the method "sc1-> method ();" on, it outputs a text that contains a counter from the call. Then we delete sc1 again. In the next step we create a pointer to the class with "Singleton * sc2 = Singleton :: getInstance ();" and call the method "sc2-> method ();" on. It should now be clear what a singleton pattern does! We will use this pattern later in the SFML tutorial, e.g. to instantiate the game class.

Comments on this post