Chapter 10. The Singleton Pattern
In this chapter, we take a look at the (in-)famous Singleton pattern. I know, you may already be acquainted with Singleton, and you may already have a strong opinion about it. It is even possible that you consider Singleton an antipattern and thus ask yourself how I mustered the courage to include it in this book. Well, I am aware that Singleton is not particularly popular and in many circles has a rather bad reputation, in particular because of the global nature of Singletons. From that perspective, however, it might be very surprising to learn that there are a couple of “Singleton”-like instances in the C++ Standard Library. Seriously! And, honestly, they work fantastically! Therefore, we should seriously talk about what a Singleton is, when Singleton works, and how to deal with Singleton properly.
In “Guideline 37: Treat Singleton as an Implementation Pattern, Not a Design Pattern”, I will explain the Singleton pattern and demonstrate how it works by a very commonly used implementation, the so-called Meyers’ Singleton. I will, however, also make a strong argument to not treat Singleton as a design pattern but as an implementation pattern.
In “Guideline 38: Design Singletons for Change and Testability”, we accept the fact that sometimes we need a solution to represent the few global aspects in our code. This is what the Singleton pattern is often used for. This also means that we are confronted by the usual problems of Singletons: global state; ...
Get C++ Software Design now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.