代码改变世界

java单例的几种实现方法

  Rollen Holt  阅读(2105)  评论(0编辑  收藏  举报

java单例的几种实现方法:

方式1:

public class Something {
    private Something() {}

    private static class LazyHolder {
        private static final Something INSTANCE = new Something();
    }

    public static Something getInstance() {
        return LazyHolder.INSTANCE;
    }
}

方式2:

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

方式3:

public class Singleton {
    private static final Singleton instance;

    static {
        try {
            instance = new Singleton();
        } catch (Exception e) {
            throw new RuntimeException("Darn, an error occurred!", e);
        }
    }

    public static Singleton getInstance() {
        return instance;
    }

    private Singleton() {
        // ...
    }
}

方式4:

public enum Singleton {
    INSTANCE;
    public void execute (String arg) {
        // Perform operation here 
    }
}

方式5:

public class SingletonDemo {
    private static volatile SingletonDemo instance;
    private SingletonDemo() { }

    public static SingletonDemo getInstance() {
        if (instance == null ) {
            synchronized (SingletonDemo.class) {
                if (instance == null) {
                    instance = new SingletonDemo();
                }
            }
        }

        return instance;
    }
}

方式6:

使用apache commons lang: LazyInitializer

 public class ComplexObjectInitializer extends LazyInitializer<ComplexObject> {
     @Override
     protected ComplexObject initialize() {
         return new ComplexObject();
     }
 }

 // Create an instance of the lazy initializer
 ComplexObjectInitializer initializer = new ComplexObjectInitializer();
 ...
 // When the object is actually needed:
 ComplexObject cobj = initializer.get();

方式7:

使用guava:

 private static final Supplier<String> tokenSup = Suppliers.memoize(new Supplier<String>() {
        @Override
        public String get() {
        	//do some init
        	String result = xxx;
            return result;
        }
    });
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示