单例模式
/**
* 单例模式:
* 保证一个类仅有一个实例,并提供一个访问它的全局方法
*
* 作用:
* 保证这个类没有其他实例被可以被创建
*/
几种不同的实现方法
public enum EnumSingleInstance {
INSTANCE;
}
public class NotLazySingleInstance {
private volatile static NotLazySingleInstance mInstance=new NotLazySingleInstance();
private NotLazySingleInstance() {
Log.d("meee",getClass()+":\n"+"NotLazySingleInstance:初始化");
}
public static NotLazySingleInstance getInstance(){
return mInstance;
}
}
public class LazySingleInstance {
private volatile static LazySingleInstance mInstance;
private LazySingleInstance() {
}
public static LazySingleInstance getInstance(){
if (mInstance==null){
synchronized (LazySingleInstance.class){
if (mInstance==null){
mInstance=new LazySingleInstance();
}
}
}
return mInstance;
}
}
public class SuperSingleInstance {
private SuperSingleInstance() {
Log.d("meee",getClass()+":\n"+"SuperSingleInstance:初始化");
}
private static class InnerClass{
static SuperSingleInstance instance=new SuperSingleInstance();
}
/**
* 静态成员的创建时机是
* 第一次引用类的任何成员时执行静态创建操作
*
* 通过静态内部类就可以实现第一次调用该方法时执行创建操作
*/
public static SuperSingleInstance getInstance(){
return InnerClass.instance;
}
}