`
catmimigo
  • 浏览: 8189 次
  • 性别: Icon_minigender_1
  • 来自: 天津
最近访客 更多访客>>
社区版块
存档分类
最新评论

Singleton 单列模式的java实现(转)

阅读更多
Singleton 单列模式在实际应用的机会很多。

最近刚好碰到,所以顺便总结了下。

一、最常见的实现如下:(不支持多线程)

public class Singleton

{

private static Singleton singleton=null;

private Singleton(){}

public static Singleton instance()

{

if(singleton==null)

singleton = new Singleton();

return singleton

return singleton;

}

}



二、如果要在多线程环境下使用,那么可以用:

public class Singleton

{

private volatile static Singleton singleton=null;

private Singleton(){}

public static Singleton getInstance()

{

if(singleton==null)

{

synchronized(Singleton.class)

{

if(singleton==null)

{

singleton=new Singleton();

}

}

}

return singleton;

}

}



该实现,有另外实现方式:


public class Singleton

{

private static Singleton singleton = new Singleton();

private Singleton();

public static Singleton getInstance()

{

return singleton;

}

}


三、The solution of Bill Pugh,直接拷贝来的。

public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}

/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}



建议大家使用第三种。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics