/**
* @author XQQ
* @create 2019-03-11 17:10
* @desc 饿汉式单例
* 1、缺点浪费内存空间
**/
public class EhsSingle {
private EhsSingle (){}
private final static EhsSingle e=new EhsSingle();
public static EhsSingle GetInstance(){
return e;
}
}
//--------------------------------------
/**
* @author XQQ
* @create 2019-03-11 17:12
* @desc 懒汉式单例
* 1、缺点性能问题。阻塞
**/
public class LazySimple {
private static LazySimple l=null;
private LazySimple (){}
public synchronized static LazySimple get(){
if(l==null){
l=new LazySimple();
}
return l;
}
}
/**
* @author XQQ
* @create 2019-03-11 17:32
* @desc 1/性能和内存都优化了
**/
public class LazyS {
private static LazySimple l=null;
private LazyS (){}
public static LazySimple get(){
if(l==null){
synchronized (LazyS.class) {
if(l==null) {
l = new LazySimple();
}
}
}
return l;
}
}
/**
* @author XQQ
* @create 2019-03-11 17:44
* @desc 类部类实现单例
* 但是还是有问题。存在。同反射也是可以实例化多个
**/
public class LazySn {
private LazySn (){}
//懒汉式单例,加final,方法不能重写
public static final LazySn laz(){
return aa.s;
}
//饿汉式单例
private static class aa{
public static final LazySn s=new LazySn();
}
}
/**
* @author XQQ
* @create 2019-03-11 17:56
* @desc 这样破坏了单例
**/
public class LazyProxy {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<LazySn> declaredConstructor = LazySn.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazySn lazySn = declaredConstructor.newInstance();
System.out.println(lazySn);
LazySn lazySn2 = declaredConstructor.newInstance();
System.out.println(lazySn2);
}
}
-----------------两个实例
top.xiequanquan.demo.basic.LazySn@1540e19d
top.xiequanquan.demo.basic.LazySn@677327b6
当然以上的都不能保证单例。比如反射,序列化 等可以破解