Generic Singleton design pattern

Quick article how to implement generic Singleton.

M.Khalil ANEBDOUR
2 min readDec 25, 2019

What is Singleton design pattern?

it’s a way to instantiate one and only instance of a class, imagine you want to code a chat room application, and you know that all users should be connected and use the same room, in this case you should have one and only instance of Room class, even if other coder in another module tries to instantiate the class Room, he or she will get the same instance as you, So this is Why Singleton design pattern. But can we make it general, I mean make a template that can take any other class and generate for you a singleton class without duplicate the logic of the code at any time ? imagine in part of your code you realize that you need a singleton what should you do ?.

Generic Singleton design pattern

Simple implementation of Generic Singleton

This template class content a private instance of class and two static method one for instantiate the class and the other one for destroying the instance, and now you can apply this template to any class to generate a singleton for you, you don’t need to write the same logic of the code any time

for example if you want to create a singleton for a Room class you can use this generic class,

Room* room = singleton< Room>::CreateInstance();

and later in your code you realize that you need another one, without change your code, you’re only going to use this generic class:

Canal* canal = singleton< Canal>::CreateInstance();

and you’re done with it.

And you can apply this logic to any other design pattern Strategy, factory method or ….

Find me on Github

And feel free to leave your feedback for me.

Thanks

--

--

M.Khalil ANEBDOUR

Financial market R&D engineer, Eager to learn new things. ✌🏼