单例模式

1.对于性能要求不高,可以这样写

 public class Singleton_1 {
    private static Singleton_1 uniqueInstance;
    //其他变量

    private Singleton_1(){}

    public static synchronized Singleton_1 getInstance(){
        if (uniqueInstance == null){
            uniqueInstance = new Singleton_1();
        }
        return uniqueInstance;
    }

    //其他方法
}

2.静态初始化的方式,非动态实例化;适于创建和运行时负担不是太重,eagerly创建单例

public class Singleton_2 {
    private static Singleton_2 uniqueInstance = new Singleton_2();
    //其他变量

    private Singleton_2(){}

    public static synchronized Singleton_2 getInstance(){
        return uniqueInstance;
    }

    //其他方法
}

3.双重检验加锁,从而减少使用synchronized(只有一次),提高性能

public class Singleton_3 {
    private volatile static Singleton_3 uniqueInstance;//volatile关键字保证读取过程变量的值保持不变
    //其他变量

    private Singleton_3(){}

    public static synchronized Singleton_3 getInstance(){
        if (uniqueInstance == null){
            synchronized (Singleton_3.class){
                if (uniqueInstance == null){
                    uniqueInstance = new Singleton_3();
                }
            }
        }
        return uniqueInstance;
    }

    //其他方法
}

更多:如何正确地写出单例模式http://www.importnew.com/21141.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值