Singleton Design Pattern in C#
Ensures a class has only one instance and provide a global point of access to it.
This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.
using System;
class MainApp
{
static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}
// Wait for user
Console.Read();
}
}
// "Singleton"
class Singleton
{
private static Singleton instance;
// Note: Constructor is 'protected'
protected Singleton()
{
}
public static Singleton Instance()
{
// Use 'Lazy initialization'
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Objects are the same instance
List of Singleton examples
C# examples
- Singleton in C# <=[You are here]
C++ examples
Delphi examples
Java examples
PHP examples
|
This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License |
