Singleton單例模式實現方法
阿新 • • 發佈:2018-12-15
單例模式原理:
單例模式又叫做 Singleton模式,指的是一個類,在一個JVM裡,只有一個例項存在。
關鍵要實現三點:
1. 構造方法私有化,使得外部無法通過new 得到新的例項 2. 靜態屬性指向例項,使整個類只有一個例項屬性值 3. public static的 getInstance方法,返回第二步的靜態屬性,外部只能從該方法獲得例項
實現方法:
public class SingletonTest2 { //建構函式私有 private SingletonTest2() { } //定義私有靜態屬性,指向生成的唯一例項 private static SingletonTest2 instance; //外部可訪問的方法,返回私有靜態屬性 public static SingletonTest2 getInstance() { if (null == instance) { instance = new SingletonTest2(); } return instance; } }