Singleton Pattern

Role

The purpose of the Singleton pattern is to ensure that there is only one instance of a class, and that there is a global access point to that object. The pattern ensures that the class is instantiated only once and that all requests are directed to that one and only object. Moreover, the object should not be created until it is actually needed. In the Singleton pattern, it is the class itself that is responsible for ensuring this constraint, not the clients of the class.

Illustration

Any class or subsystem that defines a data bank or provides access to applications, devices, or windows would benefit from the Singleton pattern. Take for example the Mac OS X Dock, shown in Figure 5-4. The Dock shows all the applications that a user accesses regularly. Those that are open have a little black arrow (Tiger) or white dot (Leopard) under them. In this case, reading from the left, Mac OS X, Preferences, Thunderbird, Firefox, Flickr Upload, Parallels for Windows, and Microsoft Word are open. Skype, Seamonkey, iPhoto, and VPUML are closed; they will be opened only when needed.

Singleton pattern illustration—the Mac Dock

Figure 5-4. Singleton pattern illustration—the Mac Dock

In most cases, when an open application's icon is clicked, Mac OS X will immediately pass control to that application and make its window visible on the screen. This is an example of the Singleton pattern: there is one instance of the application, ...

Get C# 3.0 Design Patterns 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.