# 单例模式
# 简介
创建型模式,避免对象频繁创建,节省JVM内存占用
# 示例
饿汉模式
@Slf4j public class HungrySingleton { private HungrySingleton() { } private static HungrySingleton instance = new HungrySingleton(); public static HungrySingleton getInstance() { return instance; } public void sayHi(String name){ log.info("Hi, {}", name); } }
懒汉模式 - double check 锁 + volatile
@Slf4j public class LazySingleton_1 { private LazySingleton_1() { } private static volatile LazySingleton_1 instance; public static LazySingleton_1 getInstance() { if (null == instance) { synchronized (LazySingleton_1.class) { if (null == instance) { instance = new LazySingleton_1(); } } } return instance; } public void sayHi(String name){ log.info("Hi, {}", name); } }
懒汉模式 - 类级内部类
@Slf4j public class LazySingleton_2 { private LazySingleton_2() { } /** * 类级内部类 */ private static class LazySingletonHolder { private static LazySingleton_2 instance = new LazySingleton_2(); } public static LazySingleton_2 getInstance() { return LazySingletonHolder.instance; } public void sayHi(String name){ log.info("Hi, {}", name); } }
枚举单例(《高效java》推荐写法)
@Slf4j public enum EnumSingleton { INSTANCE; public void sayHi(String name){ log.info("Hi, {}", name); } }