C++ In Theory: The Singleton Pattern, Part I (Page 1 of 5 )
There is a great book called “Design Patterns” [Gamma] that encapsulates knowledge trapped inside the heads of experienced programmers, presenting it in understandable and useable chunks. Solutions to a lot of design problems often turn out to be the same, even when programmers discover them independently. Instead of providing these solutions to you in code format, the “Design Patterns” book presents the thoughts and reasoning behind the solutions along with example code.
Design Patterns are a great way to get a head start on solving that problem you have encountered or might yet have to encounter. In this article we are going to implement a class with simple logging functionality that will make use of the Singleton pattern. My intention is not to present you with a class that will end all your logging woes, but rather to use it to demonstrate why you need this pattern.
Writing to a log is an action where it makes sense to have only one single log object active at any time you want to register data with it. It doesn’t matter which part of your application is writing to the log, as long as all parts are using the same log.
In an older programming language such as C you might choose global variables and global functions to implement such facilities, but as a project grows larger the risk of adding subtle bugs grows as well. These global variables and global functions all end up in the global namespace, and the introduction of a foreign library (or any new code for that matter) might cause naming collisions (meaning there are multiple variables/functions sharing the same name/identifier). Such collisions can only be resolved by changing the names of your own global variables and/or functions; these changes are bug prone and quite a chore in large projects with a lot of source files.
The benefit of the Singleton pattern (which can be implemented in C++) is that it prevents you from filling up the global namespace. You can keep the variables and functions locked up inside a class and restrict access to it by implementing a single point of access, which prevents you from creating multiple instances of the class. Other great features of the C++ language such as polymorphism (changing the behavior of a class through virtual functions) remain available to you as well.