好的,下面是懒汉模式和饿汉模式的单例模式实现,以及相应的测试类。 ### 懒汉模式 ```java public class LazySingleton { // 私有构造方法,防止外部实例化 private LazySingleton() {} // 静态变量,用于存储唯一的实例 private static LazySingleton instance; // 提供一个静态方法,返回唯一的实例 public static synchronized LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; } } ``` ### 饿汉模式 ```java public class EagerSingleton { // 静态变量,在类加载时就初始化 private static final EagerSingleton instance = new EagerSingleton(); // 私有构造方法,防止外部实例化 private EagerSingleton() {} // 提供一个静态方法,返回唯一的实例 public static EagerSingleton getInstance() { return instance; } } ``` ### 测试类 ```java public class SingletonTest { public static void main(String[] args) { // 测试懒汉模式 LazySingleton lazyInstance1 = LazySingleton.getInstance(); LazySingleton lazyInstance2 = LazySingleton.getInstance(); System.out.println("懒汉模式: " + (lazyInstance1 == lazyInstance2)); // 输出 true // 测试饿汉模式 EagerSingleton eagerInstance1 = EagerSingleton.getInstance(); EagerSingleton eagerInstance2 = EagerSingleton.getInstance(); System.out.println("饿汉模式: " + (eagerInstance1 == eagerInstance2)); // 输出 true } } ``` ### 注意事项 1. **线程安全**:懒汉模式在多线程环境下可能会出现问题,因为多个线程可能同时进入 `if (instance == null)` 判断,导致创建多个实例。可以通过 `synchronized` 关键字解决,但会影响性能。 2. **延迟加载**:懒汉模式实现了延迟加载,即在第一次调用 `getInstance` 方法时才创建实例,而饿汉模式在类加载时就创建了实例。 3. **性能**:饿汉模式由于在类加载时就创建了实例,所以不存在线程安全问题,但可能会浪费资源,特别是当实例占用大量内存时。 希望这些代码和注意事项对你有帮助!如果有任何问题,欢迎随时提问。 [2024-11-21 20:41:59 | AI写代码神器 | 512点数解答]