酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

四、单例模式(复习) 1、网站的计数器,一般也是采用单例模式实现,如果你存在多个计数器,每一个用户的访问都刷新计数器的值,这样的话你的实计数的值是难以同步的。根据结构图写出计数器的懒汉模式和饿汉模式的完整java代码(包括测试类)。 以下是单例模式(singleton)结构图 singleton singleton类,定义一个get instance操作,允许 -instance :singleton 客户访问它的唯一实例,getinstance是一个静态 singleton 0 方法,主要负责创建自己的唯一实例

以下是单例模式中计数器的懒汉模式和饿汉模式的 Java 代码及测试类: ```java // 饿汉模式 class CounterEager { private static CounterEager instance = new CounterEager(); private CounterEager() {} public static CounterEager getInstance() { return instance; } } // 懒汉模式 class CounterLazy { private static CounterLazy instance; private CounterLazy() {} public static CounterLazy getInstance() { if (instance == null) { instance = new CounterLazy(); } return instance; } } // 测试类 public class CounterTest { public static void main(String[] args) { CounterEager eagerCounter1 = CounterEager.getInstance(); CounterEager eagerCounter2 = CounterEager.getInstance(); System.out.println(eagerCounter1 == eagerCounter2); // 应输出 true CounterLazy lazyCounter1 = CounterLazy.getInstance(); CounterLazy lazyCounter2 = CounterLazy.getInstance(); System.out.println(lazyCounter1 == lazyCounter2); // 应输出 true } } ``` 对于这段代码,需要注意以下 3 点逻辑: 1. 懒汉模式在多线程环境下可能会出现线程安全问题,需要考虑同步机制。 2. 饿汉模式在类加载时就创建实例,可能会造成资源浪费,如果实例创建开销大且不一定会使用到,就不太适合。 3. 测试类中的比较操作是为了验证单例模式是否成功,确保获取到的实例始终是同一个。 [2024-11-21 20:44:14 | AI写代码神器 | 379点数解答]

相关提问