| 1) 构造器私有化 (防止 new ) |
| 2) 类的内部创建对象 |
| 3) 向外暴露一个静态的公共方法。getInstance |
| package com.atguigu.singleton.type1; |
| |
| public class SingletonTest01 { |
| |
| public static void main(String[] args) { |
| |
| Singleton instance = Singleton.getInstance(); |
| Singleton instance2 = Singleton.getInstance(); |
| System.out.println(instance == instance2); |
| System.out.println("instance.hashCode=" + instance.hashCode()); |
| System.out.println("instance2.hashCode=" + instance2.hashCode()); |
| } |
| |
| } |
| |
| |
| class Singleton { |
| |
| |
| private Singleton() { |
| |
| } |
| |
| |
| private final static Singleton instance = new Singleton(); |
| |
| |
| public static Singleton getInstance() { |
| return instance; |
| } |
| |
| } |
| 1) 优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。 |
| 2) 缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费 |
| 3) 这种方式基于classloder机制避免了多线程的同步问题,不过,instance在类装载时就实例化,在单例模式中大多数都是调用getInstance方法, |
| 但是导致类装载的原因有很多种,因此不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化instance就没有达到lazy loading的效果 |
| 4) 结论:这种单例模式可用,可能造成内存浪费 |
| package com.atguigu.singleton.type2; |
| |
| public class SingletonTest02 { |
| |
| public static void main(String[] args) { |
| |
| Singleton instance = Singleton.getInstance(); |
| Singleton instance2 = Singleton.getInstance(); |
| System.out.println(instance == instance2); |
| System.out.println("instance.hashCode=" + instance.hashCode()); |
| System.out.println("instance2.hashCode=" + instance2.hashCode()); |
| } |
| |
| } |
| |
| |
| class Singleton { |
| |
| |
| private Singleton() { |
| |
| } |
| |
| |
| private static Singleton instance; |
| |
| static { |
| instance = new Singleton(); |
| } |
| |
| |
| public static Singleton getInstance() { |
| return instance; |
| } |
| |
| } |
| 1) 这种方式和上面的方式其实类似,只不过将类实例化的过程放在了静态代码块中,也是在类装载的时候,就执行静态代码块中的代码,初始化类的实例。优缺点和上面是一样的。 |
| 2) 结论:这种单例模式可用,但是可能造成内存浪费 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南