标签:定义 常见 roi TE singleton tin vol 函数 default
首先了解一些单例模式的概念。
确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。
这样做有以下几个优点
其实单例有很多种实现方式,但是个人比较倾向于其中1种。可以见单例模式
代码如下
public class Singleton {
private static volatile Singleton instance = null;
private Singleton(){
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
要保证单例,需要做一下几步
而在Android中,很多地方用到了单例。比如EventBus中的单例
private static volatile EventBus defaultInstance;
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
标签:定义 常见 roi TE singleton tin vol 函数 default
原文地址:https://www.cnblogs.com/xl-phoenix/p/9252254.html