设计模式之单例模式 2020-02-06 设计模式 Java, 单例模式 评论 1、饿汉式1234567891011public class HungerSingleObject { private static HungerSingleObject instance = new HungerSingleObject(); private HungerSingleObject() { } public static HungerSingleObject getInstance() { return instance; } public void showMessage() { System.out.println("this is singleton pattern"); }} 2、懒汉式 线程不安全123456789101112131415public class LazySingleObject { private static LazySingleObject instance; private LazySingleObject() { } public static LazySingleObject getInstance() { if(instance == null) { instance = new LazySingleObject(); } return instance; } public void showMessage() { System.out.println("this is lazy single pattern"); }} 3、懒汉式 线程安全 加同步锁12345678910111213public class SyncLazySingleObject { private static SyncLazySingleObject instance; private SyncLazySingleObject() {} public static synchronized SyncLazySingleObject getInstance() { if(instance == null) { instance = new SyncLazySingleObject(); } return instance; } public void showMessage() { System.out.println("this is synchronized lazy single pattern"); }}