所谓单例模式是指只有一个实例出现,其实现步骤是1.构造方法私有化,对外提供一个获取实例的方法
1.饿汉式
public class HungrySingletion {
private final static HungrySingletion instance = new HungrySingletion();
private HungrySingletion(){}
public static HungrySingletion getInstances(){
return instance;
}
}
静态的属性,直接在类加载的时候实例化一次,以后不会再实例化了;优点是效率比较高,缺点是浪费内存
还可以用静态代码块来写:
public class HungrySingletion {
private final static HungrySingletion instance;
static{
instance = new HungrySingletion();
}
private HungrySingletion(){}
public static HungrySingletion getInstances(){
return instance;
}
}
两种写法差不多。
2.懒汉式
被外部调用的时候采取创建实例,双锁检查机制
public class DoubleCheckSingleton {
private volatile static DoubleCheckSingleton instance;//防止指令重排
private DoubleCheckSingleton(){}
public static DoubleCheckSingleton getInstance(){
if (instance == null){
synchronized(instance){
if (instance == null){
instance = new DoubleCheckSingleton();
}
}
}
return instance;
}
}
静态内部类的写法:
public class LazyStaticInnerClassSingleton {
private LazyStaticInnerClassSingleton() {
if (InnerClass.instance != null) {
throw new RuntimeException("非法访问");
}
}
public static LazyStaticInnerClassSingleton getInstance(){
return InnerClass.instance;
}
public static class InnerClass {
private static final LazyStaticInnerClassSingleton instance = new LazyStaticInnerClassSingleton();
}
}
这种写法利用了java语言的有特点,提高了并发性能,同时也能保证线程安全,缺点是可以被反射破坏
枚举写法:
public enum SingletonEnum {
INstance;
private Object data;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public static SingletonEnum getInstance(){
return INstance;
}
}
可以防止被反射破坏,因为枚举本身不能被反射调用创建实例。
防止反序列化破坏单例:
public class SeriableSingleton implements Serializable {
private final static SeriableSingleton instance = new SeriableSingleton();
private SeriableSingleton(){}
public static SeriableSingleton getInstance(){
return instance;
}
//可以防止序列化和反序列化的过程中重新创建实例
public Object readResolve(){
return instance;
}
}
针对线程的单例:
public class ThreadSingleton {
private static ThreadLocal<ThreadSingleton> th = new ThreadLocal<ThreadSingleton>() {
@Override
protected ThreadSingleton initialValue() {
return new ThreadSingleton();
}
};
private ThreadSingleton() {
}
public static ThreadSingleton getInstance() {
return th.get();
}
}