Let’s start with something simple. Singleton is probably the most basic of design patterns. When someone explains the term design pattern, you can be sure that, at some point, he will mention the singleton.
I won’t go through the whole theory, there are a way to many good sources, that explain singleton well already. I’ll just focus on the code. So we would like to have a single, one and only globally accessible instance of a certain class in our program. There are couple steps we need to do:
- Have some place to store the instance – static variable.
- Have some way of globally accessing the instance – static method.
- Prevent any other way of instantiation the class – disable constructor.
Implementation in C++ is pretty straight-forward. All the tasks mentioned above are easy to achieve with C++. Here is the code:
You can download the whole code here.
In Python situation gets a little bit stickier, but it’s not that hard to produce a singleton class as well. The problem is, that there’s no such a thing as private constructor in Python. So, you need to find another way of preventing multiple instantiation of the class. This can be achieved by raising an exception in constructor which works ok, but some might not consider that a good practice since exceptions should be use only for errors. Let’s have look at the code:
Again, you can get the whole thing here.