Chapter 5. One-of-a-Kind Objects: The Singleton Pattern
Our next stop is the Singleton Pattern, our ticket to creating one-of-a-kind objects for which there is only one instance, ever. You might be happy to know that of all patterns, the Singleton is the simplest in terms of its class diagram; in fact, the diagram holds just a single class! But don’t get too comfortable; despite its simplicity from a class design perspective, it’s going to require some deep object-oriented thinking in its implementation. So put on that thinking cap, and let’s get going.
Developer: What use is that?
Guru: There are many objects we only need one of: thread pools, caches, dialog boxes, objects that handle preferences and registry settings, objects used for logging, and objects that act as device drivers to devices like printers and graphics cards. In fact, for many of these types of objects, if we were to instantiate more than one we’d run into all sorts of problems like incorrect program behavior, overuse of resources, or inconsistent results.
Developer: Okay, so maybe there are classes that should only be instantiated once, but do I need a whole chapter for this? Can’t I just do this by convention or by global variables? You know, like in Java, I could do it with a static variable.
Guru:
Get Head First Design Patterns, 2nd Edition 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.