Program.cs
2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Ensure a class has only one instance and provide a global point of access to it.
namespace Singleton
{
/// <summary>
/// MainApp startup class for Structural
/// Singleton Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
// Test for same instance
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}
// Wait for user
Console.ReadKey();
}
}
/// <summary>
/// The 'Singleton' class
/// </summary>
sealed class Singleton
{
private static Singleton _instance;
private static readonly object padlock = new object();
// Constructor is 'private'
private Singleton()
{
}
public static Singleton Instance()
{
// Uses lazy initialization.
// Note: this is thread safe.
lock (padlock)
{
if (_instance == null)
{
_instance = new Singleton();
}
}
return _instance;
}
}
public sealed class SingletonWithOutLock
{
private static readonly SingletonWithOutLock instance = new SingletonWithOutLock();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SingletonWithOutLock()
{
}
private SingletonWithOutLock()
{
}
public static SingletonWithOutLock Instance
{
get
{
return instance;
}
}
}
public sealed class Singleton4Framework
{
private static readonly Lazy<Singleton4Framework> lazy =
new Lazy<Singleton4Framework>(() => new Singleton4Framework());
public static Singleton4Framework Instance { get { return lazy.Value; } }
private Singleton4Framework()
{
}
}
}