欢迎访问宙启技术站
智能推送

单例模式在Java中的实现函数

发布时间:2023-08-12 08:40:20

在Java中,可以使用以下几种方式来实现单例模式:

1. 饿汉式单例模式:

public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {}

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

在饿汉式单例模式中,静态变量instance在类加载时就会初始化,所以实现了线程安全。

2. 懒汉式单例模式(非线程安全):

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

在懒汉式单例模式中,getInstance()方法中延迟了实例化操作,但是在多线程环境下可能会出现线程安全问题,因为多个线程可以同时进入if(instance == null)判断。

3. 懒汉式单例模式(线程安全):

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

在懒汉式单例模式中,通过在getInstance()方法上加上synchronized关键字,实现了线程安全。

4. 双重检验锁单例模式(线程安全):

public class Singleton {
    private volatile static Singleton instance;

    private Singleton() {}

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

双重检验锁单例模式在懒汉式单例模式的基础上添加了一个额外的判断,在实例化对象之前进行了一次检查,从而提高了性能。

5. 静态内部类单例模式(线程安全):

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

    private Singleton() {}

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

静态内部类单例模式通过静态内部类的特性,在类加载时实例化Singleton对象,从而实现了线程安全和延迟加载。

以上是几种常见的单例模式的实现方式,在具体的应用中,可以根据需求选择合适的实现方式来实现单例模式。