Singleton design pattern
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| C# Design Patterns |
|
| edit |
| C# design pattern in a nutshell | |
| The Singleton design pattern is a way of ensuring that only a single instance of a class exists and of providing a single method of gaining access to it. | |
The Singleton design pattern is the most widely known pattern and the simplest of all patterns: The class diagram comprises a single class—the Singleton.
Use the Singleton design pattern when there must be only one instance of a class and it must be accessible to clients via a known access point.
| C# design pattern at a glance | |
|
Singleton is a class which permits itself to be instantiated only once. It
|
Singleton can be used—in fact, is required—in many situations, for example:
|
[edit]
Classic Singleton design pattern
The classic Singleton design pattern is often seen and quoted; however, it has a major flaw—it is not thread safe. Therefore, do not use it. It is shown here; so, it can be shown where its fault lies.
[edit]
C# example of classic Singleton design pattern (lazy instantiation, thread unsafe)
// WARNING: This code is not thread safe! using System; public sealed class Singleton { private static Singleton singleton; private Singleton() {} // private constructor public static Singleton GetInstance() { if (singleton == null) { singleton = new Singleton(); // lazy Console.WriteLine ("Singleton instantiated"); } return singleton; } } class SingletonDemo { static void Main() { Singleton objectA = Singleton.GetInstance(); Singleton objectB = Singleton.GetInstance(); // Singleton objectC = new Singleton(); - won't compile if (objectA == objectB) { Console.WriteLine ("Both refer to the same instance"); } } }
| Singleton design pattern (program output) |
| Singleton instantiated Both refer to the same instance |
[edit]
Notes on classic Singleton design pattern
- It is not essential to mark members as
private; since—unlike the Java language—, the default access is private. - It is not essential to make the class
sealed; since,Singletoncannot be subclassed already due to itsprivateconstructor. - One could just as easily use a
staticproperty namedInstancein lieu of theGetInstance()method.
- It is not essential to mark members as
public static Singleton Instance { get { if (singleton == null) { singleton = new Singleton(); } return singleton; } }
|

