单例模式
2020-08-30 本文已影响0人
five_year
饿汉模式
public class Hungry {
private Hungry() {}
private static final Hungry hungry = new Hungry();
public static Hungry getInstance() {
return hungry;
}
}
优点:没有任何的锁,执行效率比较高,用户体验好,绝对线程安全
缺点:类加载的时候就初始化,占空间、资源
懒汉模式
public class LazyOne {
private LazyOne() {
}
private static LazyOne lazy = null;
public static LazyOne getInstance() {
if (lazy == null) {
lazy = new LazyOne();
}
return lazy;
}
}
public class LazyTwo {
private LazyTwo() {
}
private static LazyTwo lazy = null;
public static synchronized LazyTwo getInstance() {
if (lazy == null) {
lazy = new LazyTwo();
}
return lazy;
}
}
public class LazyThree {
private LazyThree() {
}
public static final LazyThree getInstance() {
return LazhHolder.lazy;
}
private static class LazhHolder{
private static final LazyThree lazy = new LazyThree();
}
}
1 线程不安全
2 线程安全,但是性能不好
3 线程安全,性能好,推荐用法,可升级成反射也安全
注册登记式(枚举式) spring 就是采用这种
public class BeanFactory {
private BeanFactory() {
}
private static Map<String, Object> ioc = new ConcurrentHashMap<>();
public static Object getBean(String className) {
if (ioc.containsKey(className)) {
return ioc.get(className);
}
try {
Object obj = Class.forName(className).newInstance();
ioc.put(className, obj);
return obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}