Skip to Main Content
Head First Design Patterns
book

Head First Design Patterns

by Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra
October 2004
Intermediate to advanced content levelIntermediate to advanced
692 pages
15h 18m
English
O'Reilly Media, Inc.
Content preview from Head First Design Patterns

Chapter 5. The Singleton Pattern: One of a Kind Objects

image with no caption

Our next stop is the Singleton Pattern, our ticket to creating one-of-a-kind objects for which there is only one instance. 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, we are going to encounter quite a few bumps and potholes in its implementation. So buckle up.

image with no caption

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: In many ways, the Singleton Pattern is a convention for ensuring ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Design Patterns, 2nd Edition

Head First Design Patterns, 2nd Edition

Eric Freeman, Elisabeth Robson
Design Patterns: Elements of Reusable Object-Oriented Software

Design Patterns: Elements of Reusable Object-Oriented Software

Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

Publisher Resources

ISBN: 0596007124Errata PageSupplemental Content