package designpattern.singleton; public class HungrySingleton { private static HungrySingleton instance = new HungrySingleton();// 靜態初始化 private HungrySingleton() {// 私有化構造方法 } public static HungrySingleton GetInstance() {// 獲取實例,static的 return instance; } }
package designpattern.singleton; public class LazySingleton { private static LazySingleton instance; private LazySingleton() {// 私有化構造方法 } public static LazySingleton getInstance() {// 獲取實例,static的 if (instance == null) { instance = new LazySingleton();// 方法中創造實例 } return instance; } }
package designpattern.singleton; public class LazySingleton2 { private static LazySingleton2 instance; private LazySingleton2() { } public static synchronized LazySingleton2 getInstance() {// synchronized 修飾 if (instance == null) { instance = new LazySingleton2(); } return instance; } }
package designpattern.singleton; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LazySingleton3 { private static LazySingleton3 instance; private static Lock lock = new ReentrantLock(); private LazySingleton3() { } public static synchronized LazySingleton3 getInstance() { try { if (instance == null) { lock.lock(); if (instance == null) {// 有必要再次判斷,否則仍是存在線程安全問題 instance = new LazySingleton3(); } lock.unlock(); } } finally {// 保證鎖被釋放 lock.unlock(); } return instance; } }