-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingelton.cs
70 lines (64 loc) · 1.67 KB
/
Singelton.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
public class Singleton1
{
private static Singleton1 singleton = null;
private Singleton1() { }
public static Singleton1 GetInstance
{
get
{
if (singleton == null)
singleton = new Singleton1();
return singleton;
}
}
}
public class Singleton2
{
private static readonly Singleton2 singleton= new Singleton2();
private Singleton2() { }
public static Singleton2 GetInstance
{
get
{
return singleton;
}
}
}
public class Singleton_Eager
{
private static readonly Singleton_Eager singleton = new Singleton_Eager();
private static readonly object obj = new object();
int counter = 0;
private Singleton_Eager()
{
counter++;
Console.WriteLine(counter);
}
public static Singleton_Eager GetInstance
{
get
{
lock (obj)
{
return singleton;
}
}
}
}
public class Singleton_Lazy
{
private static readonly Lazy<Singleton_Lazy> instance = new Lazy<Singleton_Lazy>(()=>new Singleton_Lazy());
int counter = 0;
private Singleton_Lazy()
{
counter++;
Console.WriteLine(counter);
}
public static Singleton_Lazy GetInstance
{
get
{
return instance.Value;
}
}
}