实现单例应该注意以下4点:
- 构造函数不对外开放,一般为private;
- 通过一个静态方法或者枚举返回单例类对象;
- 确保单例的对象有且仅有一个,尤其是在多线程环境下;
- 䧁单例类对象在反序列化时不会被重新构建对象。
1. 饿汉单列模式
public class Singleton {
private static Singleton instance= new Singleton();
private Singleton() {};
public static Singleton getInstance() {
return instance;
}
}
2. 懒汉单列模式
public class Singleton {
private Singleton() {};
private static Singleton instance= null;
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
3. 懒汉单列模式(双重校验)
public class Singleton {
private Singleton() {};
private static Singleton instance= null;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.this){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
4. 静态内部类单列模式
public class Singleton {
private Singleton() {};
public static Singleton getInstance () {
return SingletonHolder.instance;
}
private static class SingletonHolder {
private static final Singleton instance = new Singleton();
}
}
5. 枚举单列模式
public enum Singleton {
INSTANCE;
}
6. 容器实现单列模式
public class Singleton {
private Singleton() {};
private static Map<String, Object> objects = new HashMap<String, Object>();
public static void registe (String key, Object instance) {
if (!objects.containsKey(key)) objects.put(key, instance);
}
public static Object get () {
return objects.get(key);
}
}
注:。。。
网友评论