示例代码:
1、饿汉单例模式 :
package com.example.imageloader;public class CEO {
private static final CEO mCeo = new CEO();
private CEO(){
}
public static CEO getCeo(){
return mCeo;
}
}
2、懒汉模式:
package com.example.imageloader;
public class Singleton {
private static Singleton instance;
private Singleton(){};
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
懒汉单例模式的有点事单例只有在使用时才会被实例化,在一定程度上节约了资源;缺点是第一次加载时需要及时进行实例化,反应稍慢,最大的问题是每次调用getInstance都进行同步,造成不必要的同步开销。这种模式一般不建议使用。
3、DCL实现单例
package com.example.imageloader;
public class Singleton {
private static Singleton instance = null;
private Singleton(){};
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class) {
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
4、静态内部类
package com.example.imageloader;
public class Singleton {
private Singleton() {
};
public static Singleton getInstance() {
return SingletonHolder.sInstance;
}
/**
* 静态内部类
*/
private static class SingletonHolder {
private static final Singleton sInstance = new Singleton();
}
}
这是推荐使用的单例模式实现方式
5、使用容器实现单例模式
package com.example.imageloader;
import java.util.HashMap;
import java.util.Map;
public class SingletonManager {
private static Map<String , Object> objMap = new HashMap<String, Object>();
private SingletonManager(){};
public static void registerService(String key,Object instance){
if(!objMap.containsKey(key)){
objMap.put(key, instance);
}
}
public static Object getService(String key){
return objMap.get(key);
}
}