定义
应用内只存在类的一个实例
饿汉式
public class Singleton {
public static Singleton mInstance = new Singleton();
private Singleton() {
}
public static Singleton getInstance(){
return mInstance;
}
}
懒汉式
- 方案一
public class Singleton {
public static Singleton mInstance ;
private Singleton() {
}
public static Singleton getInstance(){
if (mInstance == null) {
mInstance = new Singleton();
}
return mInstance;
}
}
存在问题:多线程并发时,可能new出多个对象
- 方案二
public class Singleton {
public static Singleton mInstance ;
private Singleton() {
}
public synchronized static Singleton getInstance(){
if (mInstance == null) {
mInstance = new Singleton();
}
return mInstance;
}
}
存在问题:多线程并发时,每个线程都需要判断一次同步锁,效率较低
- 方案三(推荐)
public class Singleton {
public static Singleton mInstance ;
private Singleton() {
}
public static Singleton getInstance(){
if (mInstance == null) {
synchronized (Singleton.class){
if (mInstance == null) {
mInstance = new Singleton();
}
}
}
return mInstance;
}
}
存在问题:存在不加关键字volatile的弊端
volatile的作用:
- 防止重排序( 1 分配一块内存空间 2 初始化对象(指向内存空间) 3赋值
多线程时2,3可能会更换顺序,出现意想不到的错误) - 线程可见(一个线程改变了公用对象,短时间内,可能对另一个线程不可见)
- 方案四(推荐)
public class Singleton {
public volatile static Singleton mInstance ;
private Singleton() {
}
public static Singleton getInstance(){
if (mInstance == null) {
synchronized (Singleton.class){
if (mInstance == null) {
mInstance = new Singleton();
}
}
}
return mInstance;
}
}
静态内部类
public class Singleton {
public static Singleton mInstance;
private Singleton() {
}
public static Singleton getInstance() {
return SingletonHolder.mInstance;
}
static class SingletonHolder {
static Singleton mInstance = new Singleton();
}
}
容器管理
public class Singleton {
public static Map<String,Object> mSingleMap = new HashMap<>();
static {
mSingleMap.put("activity_manager",new Singleton());
}
private Singleton() {
}
public static Object getInstance(String name) {
return mSingleMap.get(name);
}
}
网友评论