The Singleton Pattern
One of the simplest (yet perhaps most useful) patterns is the Singleton pattern. The entire purpose of this pattern is to ensure that only one instance of an object is ever created during the lifetime of an application.
The typical implementation of the Singleton pattern is to create a private constructor (not accessible to other classes), and then a public method that poses as a constructor but has the job of, when called, serving up the existing instance if there is one, or creating an instance if none exists.
Singletons and Multithreading
The Singleton pattern's implementation can get a bit tricky in multithreaded applications, so programmers often turn to well-tested code rather than reinventing Singleton implementations. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton, and only one may create the new instance. Also note that if the programming language has concurrent processing capabilities (as .NET languages do), the method must be constructed to execute as a mutually exclusive operation.
The classic solution to these problems is to use mutual exclusion on the class that indicates that the object is being instantiated, most often through a mutex or other thread-locking device. The Singleton pattern (Figure 8-22) is often used in conjunction with the Factory Method pattern to create a system-wide resource whose specific type is not known to the code ...
Get Programming .NET 3.5 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.