设计模式之单例模式

单例模式

意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

主要解决:一个全局使用的类频繁地创建与销毁。

何时使用:当您想控制实例数目,节省系统资源的时候。

如何解决:判断系统是否已经有这个单例,如果有则返回,如果没有则创建。

关键代码:构造函数是私有的。

饿汉模式

饿汉模式,一开始就实例化好对象,天生安全,但占用一部分空间。

public final class SingletonStarve{
    private static final SingletonStarve instance;
    static{
        instance = new SingletonStarve();
    }
    
    public static SingletonStarve getInstance(){
        return instance;
    }
    private SingletonStarve(){}
}

懒汉模式-性能低

延迟初始化,按需加载,减少空间浪费,保证了线性安全。但调用getInstance()方法需要同步,并发性能低。

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

懒汉模式-双重校验锁-性能高

这个模式将同步内容下放到if内部,提高了执行效率,不用每次获取对象时都进行同步,只有第一次同步,创建了对象之后就没必要了。只有第一次会进去,之后instance不为空,直接返回instance。保证了线性安全,同时提高了性能。

public class SingletonLazy{
    private static  volatile SingletonLazy instance = null;
    private SingletonLazy(){}
    public static  SingletonLazy getInstance(){
        if(instance == null){
            synchronized(SingletonLazy.class){
                if(instance == null){
                     instance = new SingletonLazy();//可能会重排序 
                }
            }
           
        }
        return instance;
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值