Singleton(单例模式)

一、
/**
* lazy man(不是线程安全的)
* @author TMAC-J
*
*/
public class Singleton { private static Singleton instance; private Singleton(){} public static Singleton getInstance(){
if(instance!=null){
instance = new Singleton();
}
return instance;
} } 二、
/**
* lazy man(线程安全)
* @author TMAC-J
*
*/
public class Singleton { private static Singleton instance; private Singleton(){} public static synchronized Singleton getInstance(){
if(instance!=null){
instance = new Singleton();
}
return instance;
} } 三、
/**
* hungry man(天生线程安全,缺点是类加载的时候就会实例化)
* @author TMAC-J
*
*/
public class Singleton { private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance(){
return instance;
} } 四、
这种写法和上面效果一样
public class Singleton {
private Singleton instance = null;
static {
instance = new Singleton();
}
private Singleton (){}
public static Singleton getInstance() {
return this.instance;
}
} 五、 /**
* 静态内部类
*
* @author TMAC-J
*
*/
public class Singleton { private static class SingletonHolder {
private static final Singleton instance = new Singleton();
} private Singleton(){}; public static final Singleton getSinleton(){
return SingletonHolder.instance;
}
} 六、 public enum Singleton {
INSTANCE;
} 七、
/**
* 双重锁
*
* @author TMAC-J
*
*/
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;
}
} 最常用的就是双重锁了,效率还可以

  

上一篇:charles之抓取浏览器https请求


下一篇:怎样建立一个bower私库