单例模式解析

1.什么是单例模式

一种常用的软件设计模式,它确保一个类仅有一个实例,并提供一个全局访问点来获取这个实例。

2.单例模式存在原因

(1)确保一个类仅有一个实例,并提供一个全局访问点来获取这个实例
(2)用于控制资源访问、管理共享资源(如配置文件、数据库连接等)或实现一个全局服务等多种场景。

3.如何实现一个单例模式

(1)私有构造方法
防止外部通过new关键字创建类的实例。
(2)私有静态实例
在类内部创建一个类的唯一实例,并将其声明为静态变量。
(3)公共静态方法
提供一个公共的静态方法,返回类的唯一实例,并在需要时创建这个实例。

4.具体方案:

懒汉式(线程不安全)

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

懒汉式(线程安全)

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

双重检查锁定(Double-Checked Locking)

public class Singleton {  
    // volatile关键字确保多线程的可见性和禁止指令重排序  
    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;  
    }  
}

静态内部类

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

枚举

public enum Singleton {  
    INSTANCE;  
  
    public void whateverMethod() {  
    }  
}
  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值