通常實現git
public class WithoutSingleton { public static void withoutSingletonInfo(WithoutSingleton withoutSingleton){ System.out.println("WithoutSingleton.hashCode = " + withoutSingleton.hashCode()); } }
public static void main(String[] args) { WithoutSingleton withoutSingleton = new WithoutSingleton(); WithoutSingleton.withoutSingletonInfo(withoutSingleton); WithoutSingleton withoutSingleton2 = new WithoutSingleton(); WithoutSingleton.withoutSingletonInfo(withoutSingleton2); WithoutSingleton withoutSingleton3 = new WithoutSingleton(); WithoutSingleton.withoutSingletonInfo(withoutSingleton3); }
WithoutSingleton.hashCode = 2083479002 WithoutSingleton.hashCode = 163238632 WithoutSingleton.hashCode = 1215070805
懶漢式單例模式github
public class LazySingleton { private static LazySingleton lazySingleton = null; private LazySingleton(){ } public static LazySingleton getInstance(){ if(lazySingleton == null){ lazySingleton = new LazySingleton(); } return lazySingleton; } public static void singletonInfo(){ System.out.println("lazySingleton.hashCode = " + lazySingleton.hashCode()); } }
測試類:
public static void main(String[] args) { LazySingleton lazySingleton = LazySingleton.getInstance(); lazySingleton.singletonInfo(); LazySingleton lazySingleton2 = LazySingleton.getInstance(); lazySingleton2.singletonInfo(); LazySingleton lazySingleton3 = LazySingleton.getInstance(); lazySingleton3.singletonInfo(); }
輸出:
lazySingleton.hashCode = 1110594262 lazySingleton.hashCode = 1110594262 lazySingleton.hashCode = 1110594262
構造方法私有化。安全
線程不安全,若是多個線程同時訪問,仍會產生多個實例對象。性能
餓漢式單例模式測試
public class HungrySingleton { private static HungrySingleton hungrySingleton = new HungrySingleton(); private HungrySingleton(){ } public static HungrySingleton getInstance(){ return hungrySingleton; } public static void singletonInfo(){ System.out.println("hungrySingleton.hashCode = " + hungrySingleton.hashCode()); } }
hungrySingleton.hashCode = 1977385357 hungrySingleton.hashCode = 1977385357 hungrySingleton.hashCode = 1977385357
源碼線程
https://github.com/Seasons20/DisignPattern.git
ENDcode