You probably heard of it, you probably don't even know that you are implementing it, but you need it on your resume! Once you start to use design patterns you will find that your code structure is improving. This is a "101" article about the simplest pattern - the Singleton pattern.
The purpose of this pattern is to ensure that a class has only one instance, and provide a global point of access to it. Any class in your application that has access to its namespace doesn't have to create or initialize the singleton. The caller can access properties and methods through the singleton's instance property. The singleton will retain state across calls.
1: // Singleton pattern - Structural example
2:
3: using System;
4:
5: namespace MyApp.Singleton.Structural
6: {
7:
8: /// <summary>
9: /// MainApp startup class for Structural
10: /// Singleton Design Pattern.
11: /// </summary>
12:
13: class MainApp
14: {
15: /// <summary>
16: /// Entry point into console application.
17: /// </summary>
18:
19: static void Main()
20: {
21: // Constructor is protected -- cannot use new
22: Singleton s1 = Singleton.Instance();
23: Singleton s2 = Singleton.Instance();
24:
25: // Test for same instance
26: if (s1 == s2)
27: {
28: Console.WriteLine("Objects are the same instance");
29: }
30:
31: // Wait for user
32: Console.ReadKey();
33: }
34: }
35:
36: /// <summary>
37: /// The 'Singleton' class
38: /// </summary>
39:
40: class Singleton
41: {
42:
43: private static Singleton _instance;
44:
45: // Constructor is 'protected'
46: protected Singleton()
47: {
48: }
49:
50: public static Singleton Instance()
51: {
52: // Uses lazy initialization.
53: // Note: this is not thread safe.
54: if (_instance == null)
55: {
56: _instance = new Singleton();
57: }
58:
59:
60: return _instance;
61: }
62: }
63: }
Output:
Objects are the same instance
Note: The singleton pattern must be carefully constructed in multi-threaded applications. 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 then only one should create the new one.