单例模式

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

思维导图

单例模式

类图

在这里插入图片描述

饿汉式

public class HungryDataManager {
 
   private static final HungryDataManager mManager = new HungryDataManager();
 
   private HungryDataManager() {
    }
 
   public static HungryDataManager getInstance() {
 
       return mManager;
 
    }
}

懒汉式

public class LazyDataManager {
    private static LazyDataManagermManager;
 
    private LazyDataManager() {
 
    }
 
    public static LazyDataManagergetInstance() {
        if (mManager == null) {
            mManager = new LazyDataManager();
        }
 
        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;
    }
}

静态内部类

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;
    }
 
}
展开阅读全文

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