单例模式

  Java   4分钟   622浏览   0评论

你好呀,我是小邹。

单例模式是Java中最常用的几种设计模式之一,它的目标是确保一个类只有一个实例,并提供一个全局访问点。

单例模式的实现

懒汉式

这是最简单的单例模式实现方式,但在多线程环境下可能会出现问题。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

线程安全的懒汉式

通过synchronized关键字,我们可以确保getInstance()方法在多线程环境下的安全性。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

双重检查锁定

双重检查锁定是一种优化的懒汉式实现方式,它只在必要时对创建实例的过程进行同步。

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

饿汉式

饿汉式在类加载时就创建实例,因此没有线程安全问题。

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

    private Singleton() {}

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

枚举

枚举也是一种实现单例模式的好方法,它既简单又安全。

public enum Singleton {
    INSTANCE;

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

以上就是Java中单例模式的几种实现方式,每种方式都有其适用场景,开发者应根据实际需求选择最适合的方式。

如果你觉得文章对你有帮助,那就请作者喝杯咖啡吧☕
微信
支付宝
  0 条评论