• In the Singleton pattern, as the name suggests, there is a single instance of the object alive throughout the life of the system. This ensures that a class only has one instance, and provide a global point of access to it.
• There is a well known way to access this instance, and the accessor method is responsible for ensuring that all clients can access the singleton object.
• This pattern is very useful when all requests have to be directed to a single object. This pattern is very common in the COM model again; the CoGetClassObject API call returns a reference to a class object, which is a singleton object for that particular class. MFC applications use singleton objects to access the base class objects (like the global CWinApp instance) as well.
• In C#, this can be accomplished with a static member and static function
Singleton example:
public sealed class Singleton { /*Sealed*/
// 1. private singlton object
private static Singleton _singleton;
// 2. used to allow only one thread (Use Lock instead of Mutex)
private static Mutex mutex = new Mutex();
// 3. declare private class so no one can create instance
private Singleton() { }
// 4. Method to get singleton object
public static Singleton GetSingleton() {
// since multiple threads could be calling this, protect it
mutex.WaitOne();
if (_singleton == null)
_singleton = new Singleton();
mutex.ReleaseMutex();
return _singleton;
}
// 5. other method
public string GetData() { return "Hi"; }
}
Static class vs Singletone
This differs from the Singleton pattern in that a Singleton class is supposed to have one (and only one) *instance*, while a "static class" is never instanciated (or, at least, there is no point in instanciating it).
The Singleton pattern has several advantages over the "static class" pattern. First, a singleton can extend classes and implement interfaces, while a static class cannot (well, it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded. A sinlgeton class can be extended and it's methods overidden.
Perhaps the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance. For instance, assume you have a Configuration class that holds some global configs.
Links: