单例实现方法
1. 通过判断
private Singleton(){}
private static Singleton instance = null;
public static Singleton getInstance(){
if (instance == null){
instance = new Singleton();
}
return instance;
}
2. 使用静态成员变量
private Singleton(){}
private static Singleton instance = new Singleton();
public static singleton getInstance(){
return instance;
}
3. 利用缓存
private Singleton(){}
private Map<String,Singleton> map = new HashMap<String,Singleton>;
public Singleton getInstance(String key){
singleton instance = map.get(key);
if (instance == null ){
instance = new Singleton();
map.put(key,instance);
}
return instance;
}
4. 为1添加线程安全:同步
public static synchronized Singleton getInstance(){
....
}
5. 双重检查加锁
private Singleton(){}
private volatile static Singleton instance = null;
public static Singleton getInstance(){
if (instance == null){
synchronized(this){ //synchronized(Singleton.class)
if (instance == null){
instance = new Singleton();
}
}
}
}
6. 通过静态内部类: 比较好的实现方式(既实现了延迟加载,也保证了线程安全)
private static class SingletonHolder{
private static Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
7. 枚举: 最佳实现
enum SingletonEnum {
singleton;
//构造器
private SingletonEnum(){
System.out.println("构造器只调用一次");
}
//属性
private String attribute;
//定义方法
public void method(){}
}