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(); }