Java中的五種單例模式實現方法

package singleton;html

 * @author leijava

 * 單例模式的五種寫法:多線程

 * 一、懶漢ide

 * 二、惡漢ui

 * 三、靜態內部類spa

 * 四、枚舉線程

 * 五、雙重校驗鎖orm

 * 2011-9-6htm

 *5、 雙重校驗鎖,在當前的內存模型中無效對象

class LockSingleton{

    private volatile static LockSingleton singleton;

    private LockSingleton(){}   

    //詳見:http://www.ibm.com/developerworks/cn/java/j-dcl.html

    public static LockSingleton getInstance(){

        if(singleton==null){

            synchronized(LockSingleton.class){

                if(singleton==null){

                    singleton=new LockSingleton()

        return singleton;

 * 4、枚舉,《Effective Java》做者推薦使用的方法,優勢:不只能避免多線程同步問題,並且還能防止反序列化從新建立新的對象

 enum EnumSingleton{

    INSTANCE;

    public void doSomeThing(){

 * 3、靜態內部類 優勢:加載時不會初始化靜態變量INSTANCE,由於沒有主動使用,達到Lazy loading

class InternalSingleton{

    private static class SingletonHolder{

        private final static  InternalSingleton INSTANCE=new InternalSingleton();

    private InternalSingleton(){}

    public static InternalSingleton getInstance(){

        return SingletonHolder.INSTANCE;

 * 2、惡漢,缺點:沒有達到lazy loading的效果

class HungrySingleton{http://www.huiyi8.com/moban/ 模板

    private static HungrySingleton singleton=new HungrySingleton();

    private HungrySingleton(){}

    public static HungrySingleton getInstance(){

        return singleton;

 * 1、懶漢,經常使用的寫法

class LazySingleton{

    private static LazySingleton singleton;

    private LazySingleton(){

    public static LazySingleton getInstance(){

        if(singleton==null){

            singleton=new LazySingleton();

        return singleton;

相關文章
相關標籤/搜索