Java实现单例模式
饿汉式
静态常量饿汉式的优点是:在类装载的时候就完成实例化,没有达到Lazy Loading的效果,并且避免了线程同步问题。
它的缺点是:如果从始至终从未使用过这个实例,则会造成内存的浪费。
public class adaDemo3 {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
Singleton instance1 = Singleton.getInstance();
System.out.println(instance1==instance);
System.out.println(instance1.hashCode());
System.out.println(instance.hashCode());
}
}
class Singleton{
private final static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance(){
return instance;
}
}
懒汉式(双重检查)
效率可以,线程安全,推荐使用。
class Singleton{
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance(){
if (instance==null){
synchronized (Singleton.class){
if (instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}
懒汉式(静态内部类)
利用JVM加载类时是线程安全的机制,推荐使用。
class Singleton{
private Singleton (){}
private static class InternalClass{
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return InternalClass.instance;
}
}
枚举类
public class adaDemo3 {
public static void main(String[] args) {
Singleton instance = Singleton.INSTANCE;
Singleton instance1 = Singleton.INSTANCE;
System.out.println(instance1==instance);
System.out.println(instance1.hashCode());
System.out.println(instance.hashCode());
instance.test();
}
}
enum Singleton{
INSTANCE;
void test(){
System.out.println("test");
}
}
【推荐】国内首个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代理技术深度解析与实战指南