java单例模式

今天学了一下java中的单例模式。

最简单、成熟的单例模式是这么设计的:

public class Singleton {
   public final static Singleton INSTANCE = new Singleton();
   private Singleton() {
         // Exists only to defeat instantiation.
      }
}

这里使用pubic final static限定词使得INSTANCE在声明时(?是否等同于编译时?) 就被实例化,使用起来是这样的:

      Singleton singleton = Singleton.INSTANCE;
      singleton.dothis();
      singleton.dothat();
      ...

该方案的缺点是没有办法改变它,以便后来你可能想要允许多个单例类的实例。而且没有办法传入参数动态地生成实例。

另外一种简单成熟的方式是使用同步:

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

这种方法的缺点是有同步的开销。


见网上有解决这以上两种设计的矛盾的方法:

private static int hasInitialized=0;
private static Singleton INSTANCE;
public static Singleton getInstance(){
  if(hasInitialized==0){
    synchronized(Singelton.class){
      //Double checking
      if(hasInitialized==0){
        INSTANCE=new Singleton();
        hasInitialized=1;
      }
    }
  }
}

不确定这种方法可不可行。

以上只是今天学习的总结。具体参考 http://calmness.iteye.com/blog/60179http://www.iteye.com/topic/211471



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值