Android 单例模式
关于单例模式的优缺点和注意事项,以及各种写法
双重锁定单例(防止多线程,高并发破坏单例)改写成抽象类,想要实现单例,来继承吧
public abstract class Singleton<T> {
private volatile T mInstance;
//子类要实现的方法
protected abstract T createInstance();
public final T getInstance() {
if (mInstance == null) {
synchronized (this) {
if (mInstance == null) {
mInstance = createInstance();
}
}
}
return mInstance;
}
}
示例:TestDemo.java 单例化
public class TestDemo{
private TestDemo() {
...
}
private static final Singleton<TestDemo> sSingleton = new Singleton<TestDemo>() {
@Override
protected TestDemo createInstance() {
//方法的实现其实就是new一个对象出来
return new TestDemo();
}
};
//获取TestDemo单例的方法
public static TestDemo getInstance() {
return sSingleton.getInstance();
}
}
441

被折叠的 条评论
为什么被折叠?



