单例模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chendeshan330/article/details/80109301

饿汉式

public class HungryDataManager {

   private static final HungryDataManager mManager = newHungryDataManager();

   private HungryDataManager() {
    }

   public static HungryDataManager getInstance() {

       return mManager;

    }
}

 

懒汉式

public class LazyDataManager {
    private static LazyDataManagermManager;

    private LazyDataManager() {

    }

    public static LazyDataManagergetInstance() {
        if (mManager == null) {
            mManager = newLazyDataManager();
        }

        return mManager;
    }

}

多线程安全

public class SafeDataManager {

    private staticSafeDataManager mManager;

    privateSafeDataManager() {
    }

    public staticSafeDataManager getInstance() {

        if(mManager == null) {
           synchronized (SafeDataManager.class) {
                if(mManager == null) {
                   mManager = new SafeDataManager();
                }
            }
        }
        returnmManager;
    }
}

IoDH多线程安全

public class IoDHDataManager {
    private static final String TA =IoDHDataManager.class.getName();

    private IoDHDataManager() {

    }

    private static class ClassHolder{
        private static finalIoDHDataManager mManager = new IoDHDataManager();
    }

    public static IoDHDataManagergetInstance() {
        return ClassHolder.mManager;
    }

}

 

阅读更多
换一批

没有更多推荐了,返回首页