1.单例模式:一个类只有一个实例,并且提供一个访问该实例全局方法,例如在连接池,线程池中的使用,servlet中的使用等
2.单例模式中设计的主要的问题:效率(同步影响效率),安全(线程安全),是否可延时(资源),是否可以避免反射和反序列化漏洞(枚举获取方式)
3.饿汉式:线程安全,效率高,在类加载时初始化不能延时加载,如果没有调用赵成资源浪费
//饿汉式:线程安全,效率高,在类加载时初始化不能延时加载,如果没有调用赵成资源浪费 public class SingletonTest1 { private static SingletonTest1 instance = new SingletonTest1(); private SingletonTest1() { } public static SingletonTest1 getInstance() { return instance; } }
4.懒汉式:线程安全,因为可能需要并发操作所以效率不高,可以延迟加载避免资源浪费
//懒汉式:线程安全,因为可能需要并发操作所以效率不高,可以延迟加载避免资源浪费 public class SingletonTest2 { private volatile static SingletonTest2 instance = null; private SingletonTest2() { } public static SingletonTest2 getInstance() { if (instance == null) { synchronized (SingletonTest2.class) { if (instance == null) { return instance = new SingletonTest2(); } } } return instance; } }
5.静态内部类获取:线程安全,效率高,可以延时加载
//静态内部类获取方式:线程安全,效率高,可以延时加载 public class SingletonTest3 { private SingletonTest3() { } private static class createInstance {//类似静态方法 private static SingletonTest3 instance = new SingletonTest3(); static {//没有调用静态类不会输出 System.out.println(1111); } } public static SingletonTest3 getInstance() { return SingletonTest3.createInstance.instance; } }
6.枚举方式获取
//枚举的方式获取:线程安全,效率高,不可以延时加载,可以避免方式和反序列化的路漏洞较为安全 public enum SingletonTest4 { instance; public void test(){ } }