-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy path单例模式.cs
77 lines (65 loc) · 2.03 KB
/
单例模式.cs
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
namespace HelloDotNetGuide.设计模式
{
public class 单例模式
{
/// <summary>
/// 饿汉式单例模式
/// </summary>
public class SingletonEager
{
private SingletonEager() { }
private static readonly SingletonEager _instance = new SingletonEager();
public static SingletonEager Instance
{
get { return _instance; }
}
public void DoSomething()
{
Console.WriteLine("饿汉式单例模式.");
}
}
/// <summary>
/// 懒汉式单例模式
/// </summary>
public class SingletonLazy
{
private SingletonLazy() { }
private static SingletonLazy? _instance;
private static readonly object _lockObj = new object();
public static SingletonLazy Instance
{
get
{
if (_instance == null)
{
lock (_lockObj)
{
if (_instance == null)
{
_instance = new SingletonLazy();
}
}
}
return _instance;
}
}
public void DoSomething()
{
Console.WriteLine("懒汉式单例模式.");
}
}
/// <summary>
/// 懒加载单例模式
/// </summary>
public sealed class SingletonByLazy
{
private static readonly Lazy<SingletonByLazy> _lazy = new Lazy<SingletonByLazy>(() => new SingletonByLazy());
public static SingletonByLazy Instance { get { return _lazy.Value; } }
private SingletonByLazy() { }
public void DoSomething()
{
Console.WriteLine("懒加载单例模式.");
}
}
}
}