定義:單例模式(Singleton),保證一個類僅有一個實例,並提供一個訪問它的全局訪問點
java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DP { class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } }
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
上面的實現其實都是屬於懶漢式的實現,即引用時才進行初始化;下面介紹一下餓漢式的實現,即調用時即進行初始化
c#
JAVA版實現spa
public class ESingleton { private static final ESingleton instance = new ESingleton(); private ESingleton() { } public static ESingleton getInstance() { return instance; } }
C#版實現code
class ESingleton { private static readonly ESingleton instance = new ESingleton(); private ESingleton() { } public static ESingleton getInstance() { return instance; } }