单例模式的定义
单体模式保证一个类只有一个实例, 并提供一个全局访问该实例的方法
.Net Core实现单例模式的代码
ChocolateBoiler.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
| namespace SingletonPattern { public class ChocolateBoiler { public bool Empty { get; private set; } public bool Boiled { get; private set; }
private static ChocolateBoiler _uniqueInstance;
private ChocolateBoiler() { Empty = true; Boiled = false; }
public static ChocolateBoiler GetInstance() { return _uniqueInstance ?? (_uniqueInstance = new ChocolateBoiler()); }
public void Fill() { if (Empty) { Empty = false; Boiled = false; } }
public void Drain() { if (!Empty && Boiled) { Empty = true; } }
public void Boil() { if (!Empty && !Boiled) { Boiled = true; } } } }
|
SynchronizedChocolateBoiler.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
| using System.Runtime.CompilerServices; namespace SingletonPattern { public class SynchronizedChocolateBoiler { public bool Empty { get; private set; } public bool Boiled { get; private set; }
private static SynchronizedChocolateBoiler _uniqueInstance;
private SynchronizedChocolateBoiler() { Empty = true; Boiled = false; }
[MethodImpl(MethodImplOptions.Synchronized)] public static SynchronizedChocolateBoiler GetInstance() { return _uniqueInstance ?? (_uniqueInstance = new SynchronizedChocolateBoiler()); }
public void Fill() { if (Empty) { Empty = false; Boiled = false; } }
public void Drain() { if (!Empty && Boiled) { Empty = true; } }
public void Boil() { if (!Empty && !Boiled) { Boiled = true; } } } }
|
DoubleCheckChocolateBoiler.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
| namespace SingletonPattern { public class DoubleCheckChocolateBoiler { public bool Empty { get; private set; } public bool Boiled { get; private set; }
private static volatile DoubleCheckChocolateBoiler _uniqueInstance; private static readonly object LockHelper = new object();
private DoubleCheckChocolateBoiler() { Empty = true; Boiled = false; }
public static DoubleCheckChocolateBoiler GetInstance() { if (_uniqueInstance == null) { lock (LockHelper) { if (_uniqueInstance == null) { _uniqueInstance = new DoubleCheckChocolateBoiler(); } } } return _uniqueInstance; }
public void Fill() { if (Empty) { Empty = false; Boiled = false; } }
public void Drain() { if (!Empty && Boiled) { Empty = true; } }
public void Boil() { if (!Empty && !Boiled) { Boiled = true; } } } }
|