温馨提示×

java单例模式实现代码怎么写

小亿
76
2023-10-24 00:13:40
栏目: 编程语言

在Java中实现单例模式有多种方式,以下是其中几种常用的实现方式:

  1. 饿汉式(线程安全):
public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}
  1. 懒汉式(线程不安全):
public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. 懒汉式(线程安全,双重检查锁定):
public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  1. 静态内部类(线程安全):
public class Singleton {
    private Singleton() {}

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

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

以上是几种常用的单例模式实现方式,选择哪种方式取决于具体的需求和线程安全性要求。

0