java 中单例模式的实现方法
简介
单例模式是一种设计模式,旨在确保一个类在整个应用程序中仅存在一个实例。这种模式在控制共享资源的访问、保持状态和提供全局访问点等方面非常有用。
实现方法
1. 饿汉式单例
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}2. 懒汉式单例
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}3. 双重检查锁定
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;
}
}4. 枚举单例
public enum Singleton {
INSTANCE;
public void doSomething() {
// ...
}
}5. 静态内部类
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}选择指南
选择单例模式的实现方法应根据具体的应用需求:
例的方法,性能较好。以上是关于在 Java 中如何实现单例模式以及几种常见实现方法的详细介绍。要了解更多内容,请关注编程学习网的其他相关文章!