image.png
单例模式
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;
}
}
网友评论