【设计模式】单例模式

【设计模式】单例模式_第1张图片
image.png

单例模式

【设计模式】单例模式_第2张图片
image.png

常用单例模式:

  • 懒汉单例模式:
public class SingleInstance {
    public SingleInstance() {
    }
    private static  SingleInstance sInstance;
    public static SingleInstance getInstance(){
        synchronized (SingleInstance.class){//线程安全
            if (sInstance == null){
                sInstance = new SingleInstance();
            }
        }
        return sInstance;
    }
    
}
  • 静态内部类单例模式:
 1 public class Singleton {  
 2     private static class SingletonHolder {  
 3     private static final Singleton INSTANCE = new Singleton();  
 4     }  
 5     private Singleton (){}
 6     public static final Singleton getInstance() {  
 7         return SingletonHolder.INSTANCE;  
 8     }  
 9 }  

Android Application 中使用单例模式:

public class MyApplication extends Application {
    private static MyApplication application;
    public static MyApplication getInstance(){
        return application;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
    }
}

你可能感兴趣的:(【设计模式】单例模式)