yan061

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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");
    }
}

posted on   yan061  阅读(17)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示