定义
确保某一个类只有一个实例,并且自行实例化,向整个系统提供这个唯一实例
五种单例模式
1.饿汉式
/**
* gengwei 饿汉式
*/
public class StarvingSingletion {
private static final StarvingSingletion mInstance = new StarvingSingletion();
private StarvingSingletion(){
}
public static StarvingSingletion getInstance(){
return mInstance;
}
public void printLog(String log){
Log.e("gengwei",":"+log);
}
}
使用方式
StarvingSingletion starvingSingletion = StarvingSingletion.getInstance();
starvingSingletion.printLog("饿汉式");
2.懒汉式
/**
* gengwei 懒汉式
*/
public class SlackerSingletion {
private static SlackerSingletion mInstance;
private SlackerSingletion(){
}
/**
* gengwei synchronized线程安全,保证多线程情况下单例的唯一性
* @return
*/
public static synchronized SlackerSingletion getInstance(){
if (mInstance == null) {
mInstance = new SlackerSingletion();
}
return mInstance;
}
public void printLog(String log){
Log.e("gengwei",":"+log);
}
}
3.双重锁校验机制
/**
* gengwei 双重校验机制
*/
public class DoubleChackSingletion {
/**
* volatile 是为了防止乱序执行导致双重校验机制失效
*/
private volatile static DoubleChackSingletion mInstance;
private DoubleChackSingletion(){
}
public static DoubleChackSingletion getInstance(){
if (mInstance == null){
synchronized (DoubleChackSingletion.class) {
if (mInstance == null) {
mInstance = new DoubleChackSingletion();
}
}
}
return mInstance;
}
public void printLog(String log){
Log.e("gengwei",":"+log);
}
}
4.静态内部类
/**
* gengwei
* 静态内部类方式
*/
public class InternalClassSingletion {
private InternalClassSingletion(){
}
public static InternalClassSingletion getInstance(){
return InternalClassSingletionHolder.instance;
}
private static class InternalClassSingletionHolder {
private static final InternalClassSingletion instance = new InternalClassSingletion();
}
public void printLog(String log){
Log.e("gengwei",":"+log);
}
}
5.枚举
public enum EmumSingletion {
INSTANCE;
public void printLog(String log){
Log.e("gengwei",":"+log);
}
}
推荐使用双重校验和静态内部类的方式
网友评论