JAVA设计模式:单例(Singleton)

        单例(Singleton)设计模式保证每个类只有一个实例,并为这个实例提供一个全局的访问点。

        与工具类中的静态成员不同,单例类一般用来保存应用程序的状态数据,这些数据在应用程序的各个部分都可能被访问或修改。

        单例模式的几种实现方式。

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

    public static Singleton getInstance() {
        return instance;
    }

   /** Don't let anyone else instantiate this class */
   private Singleton() {
   }
}

        这种方式实现简单,并且保证实例的唯一性,缺点是必须先加载后使用,而且不管单例类是否真正使用到,实例总是会先被加载,这看起来相当的不妥,因而有了懒加载(Lazy Initialization)的模式。
 
public class Singleton {
    private static Singleton instance = null;

    private Singleton() {

    }

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

        这种方式可以实现懒加载,但当多个线程同时进入getInstance方法时,可能会产生多份实例,这显然违背单例模式的初衷。为了避免这种情况,考虑加上同步(synchronized)机制。

public class Singleton {
    private static Singleton instance = null;

    private Singleton(){
    }

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

        这种方式可以在懒加载的同时保证只有一份实例,但对整个getInstance方法作同步处理会带来线程同步上的性能消耗。

public class Singleton {
    private static Singleton instance;

    private Singleton(){
    }

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

      上面的方式就是所谓的Double-check Locking即双重检查和锁定模式,目前看来很完美。

      阅读全文


      更多精彩原创文章请关注笔者的原创博客: http://www.coolfancy.com

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/348874/viewspace-735429/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/348874/viewspace-735429/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值