Java设计模式: 单例模式

1.需要传递参数:

public class Singleton{
    private volatile static Singleton instance = null;
    private int value = 0;
    private Singleton(){
        value = 1024;
    }
    public static Singleton getInstance(Context context){
        if (instance == null){
            synchronized (Singleton.class){
                if (instance == null){
                    instance = new Singleton(context.getApplicationContext());
                }
            }
        }
    }
}

2.不需要传递参数

public class Singleton{
    private Singleton(){}
    public static Singleton getInstance(){
         return SingletonHolder.instance;
    }
    
    private static class SingletonHolder{
        private static final Singleton instance = new Singleton();
    }

 

posted @ 2019-05-23 10:18  夜行过客  阅读(273)  评论(0编辑  收藏  举报