- 为什么使用单例模式
- 节约内存开销,提高效率,提高资源使用率。
- 单例模式的特点
- 构造方法私有化
- 定义静态方法,并且返回当前的对象
- 确保这个对象是唯一的
- 确保序列化和反序列化操作的过程中同样保证同一个对象
- 不允许继承的
- 角色划分
- 客户端(调用)
- 单例类
- 变种
-
饿汉
public final class Singleton{ private static Singleton instance =new Singleton(); private Singleton(){ } public static Singleton getInstance(){ return instance; } }
- 优点:安全,不用关心单线程还是多线程
- 缺陷:耗费内存
-
懒汉(单线程使用)
public final class Singleton{ private static Singleton instance; private Singleton(){ } public static Singleton getInstance(){ if(instance ==null){ instance = new Singleton(); } return instance; } }
- 优点:节约内存,提高性能
- 缺点:多线程问题很难解决
- 不加锁,创建多个对象
- 加锁,阻塞,耗费性能
-
双重检查
public final class Singleton{ //volatile 去掉虚拟机优化代码,为了防止双重检查失败 //编译器编译时对以下代码做了什么事情 //Singleton instance = new Singleton() //1. 分配内存 //2. 掉用构造方法初始化参数 //3. 将instance对象指向这快内存区域 private static volatile Singleton instance; private Singleton(){ } public static Singleton getInstance(){ if(instance ==null){ synchronized(Singleton.class){ if(instance ==null){ instance = new Singleton(); } } } return instance; } }
- 优点:既能保证创建对象是单例对象,也保证了多线程安全
- 缺点:消耗性能,可以忽略不计
-
静态内部类(官方推荐,多线程使用)
public final class Singleton{ private Singleton(){ } public static Singleton getInstance(){ return SingletonHolder. instance; } public static class SingletonHolder{ private static Singleton instance =new Singleton(); } }
- 优点:既能保证内存优化, 又能保证安全
-
枚举
public enum Singleton{ instance; }
-
- 具体应用
工具类,
网友评论