温馨提示×

如何正确实现java单例类

小樊
82
2024-09-09 10:44:28
栏目: 编程语言

在Java中,要正确地实现一个单例类,可以使用以下几种方法:

  1. 懒汉式(Lazy Initialization):
public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
  1. 饿汉式(Eager Initialization):
public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}
  1. 双重检查锁定(Double-Checked Locking):
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. 静态内部类(Static Inner Class):
public class Singleton {
    private Singleton() {}

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

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
  1. 枚举(Enum):
public enum Singleton {
    INSTANCE;

    public void doSomething() {
        // ...
    }
}

以上五种方法都可以实现Java单例类。在实际项目中,可以根据需求和场景选择合适的实现方式。

0