码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式的几种写法

时间:2016-08-19 13:25:41      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:java   singleton   

1、双重校验锁(JDK1.5版本之后)

public class  Singleton
{
 private volatile static Singleton singleton;
 private Singleton(){
 }
 public static Singleton getSingleton(){
  if(singleton == null){
   synchronized(Singleton.class){
    if(singleton == null){
     singleton = new Singleton();
    }
   }
  }
  return singleton;
 }
}

2、静态内部类

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










本文出自 “阿酷博客源” 博客,谢绝转载!

单例模式的几种写法

标签:java   singleton   

原文地址:http://aku28907.blog.51cto.com/5668513/1840219

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!