When to use the singleton

The superficial answer to the question of when to use a singleton is very simple—when you need to have only one object of some type in the entire program. This answer, of course, simply kicks the can down the road—OK, so when, if ever, is it a good design principle to have only one object of some type in the entire program? There isn't an easy universal answer to this, which gives rise to the argument that, like any other global object, a singleton is a sign of bad design.

There are two general categories of design problems that can be addressed with a singleton, or, more generally, with a unique global object. The first category is objects that represent some physical object or resource, where the corresponding ...

Get Hands-On Design Patterns with C++ now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.