forked from sheng-jie/Design-Pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
82 lines (64 loc) · 2.16 KB
/
Copy pathProgram.cs
File metadata and controls
82 lines (64 loc) · 2.16 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SingletonPattern
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("单例模式:");
TestStaticSingleton();
TestLasyInitialSingleton();
TestGenericSingleton();
TestDoubleLockSingleton();
}
private static void TestStaticSingleton()
{
Console.WriteLine("静态变量初始化实例");
Singleton1 singleton1 = Singleton1.Instance();
singleton1.GetInfo();
Console.ReadLine();
}
private static void TestLasyInitialSingleton()
{
Console.WriteLine("延迟初始化实例");
Singleton2 singleton2 = Singleton2.Instance();
singleton2.GetInfo();
singleton2.Reset();
Console.ReadLine();
}
private static void TestDoubleLockSingleton()
{
Console.WriteLine("锁机制确保多线程只产生一个实例");
for (int i = 0; i < 2; i++)
{
Thread thread=new Thread(ExecuteInForeground);
thread.Start();
}
}
private static void ExecuteInForeground()
{
Console.WriteLine("Thread {0}: {1}, Priority {2}",
Thread.CurrentThread.ManagedThreadId,
Thread.CurrentThread.ThreadState,
Thread.CurrentThread.Priority);
Singleton3 singleton3 =Singleton3.Instance();
singleton3.GetInfo();
Console.WriteLine(singleton3.GetHashCode());
}
private static void TestGenericSingleton()
{
Console.WriteLine("泛型单例模式:");
Singleton4 instance = GenericSingleton<Singleton4>.GetInstance();
instance.GetInfo();
var singleton4 = Singleton4.Instance;
singleton4.GetInfo();
Console.ReadLine();
}
}
}