设计模式--单例模式Singleton

简介: 这篇文章详细介绍了单例模式Singleton的八种实现方式,包括饿汉式(静态常量和静态代码块)、懒汉式(线程不安全和线程安全的同步方法、同步代码块)、双重检查、静态内部类和枚举。每种方式都有详细的代码示例和优缺点说明,帮助理解单例模式的应用和选择适合的实现方法。

单例设计模式

单例设计模式:采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的静态方法。

单例设计模式的八种方式:

  1. 饿汉式(静态常量)
  2. 饿汉式(静态代码块)
  3. 懒汉式(线程不安全)
  4. 懒汉式(线程安全,同步方法)
  5. 懒汉式(线程不安全,同步代码块)
  6. 双重检查
  7. 静态内部类
  8. 枚举

1. 饿汉式(静态常量)

“饿汉式” ,就是你可以试着想想一下,一个饿汉的行为,肯定是见到了食物就去吃。即无论是否需要实例对象,都会在内存中去自动加载一份。

优缺点说明:

  1. 优点:写法实现简单,在类装载的时候就完成了实例化。避免了线程同步的问题。
  2. 缺点:在类装载时完成实例化,若一直没有使用过这个实例,则会造成内存资源的浪费。

这种单例模式可以使用,可能会造成资源的浪费。

代码实现:

package com.robin.singleton.type1;

public class SingletonTest1 {
   
    public static void main(String[] args) {
   
        // 测试单例模式--饿汉式(静态常量)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例
    }
}

// 单例模式----饿汉式(静态常量)

class Singleton{
   
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){
   }

    // 类加载时,即创建唯一的一份对象
    private final static Singleton instance = new Singleton();

    // 对外提供一个公共的返回 singleton 实例对象
    public static Singleton getInstance(){
   
        return instance;
    }
}

2. 饿汉式(静态代码块)

与上面第一种方式类似,只不过是将类实例化的过程放到了静态代码块中,优缺点与上面一致。

代码实现:

package com.robin.singleton.type2;

public class SingletonTest2 {
   
    public static void main(String[] args) {
   
        // 测试单例模式--饿汉式(静态代码块)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例
    }
}

// 单例模式----饿汉式(静态代码块)

class Singleton{
   
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){
   }

    private static Singleton instance ;

    // 在静态代码块中-->类加载时,完成instance的初始化
    static {
   
        instance = new Singleton();
    }

    // 对外提供一个公共的返回 singleton 实例对象
    public static Singleton getInstance(){
   
        return instance;
    }
}

3. 懒汉式(线程不安全)

“懒汉式”,当饿极了才去吃东西。即当需要时,才将类实例对象创建并且加载到内存中。

优缺点:

  1. 实现了延迟加载,但只能在单线程下使用。
  2. 在多线程下,会产生多个实例。
  3. 实际开发中,不要使用这种方式。

代码实现:

package com.robin.singleton.type3;

public class SingletonTest3 {
   
    public static void main(String[] args) {
   
        // 测试单例模式--懒汉式(线程不安全)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例

    }

}

// 单例模式----饿汉式(静态代码块)

class Singleton {
   
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton() {
   
    }

    private static Singleton instance;


    // 当使用到时,才去初始化实例对象(懒汉式)
    // 对外提供一个公共的返回 singleton 实例对象
    public static Singleton getInstance() {
   
        if (instance == null) {
   
            instance = new Singleton();
        }
        return instance;
    }
}

多线程测试:

package com.robin.singleton.type3.threadSingleton;

public class TestThreadSingleton {
   
    public static void main(String[] args) {
   
        System.out.println("~~~~~多线程测试~~~~~");
        // 多线程测试懒汉式的线程不安全的写法
        for (int i = 0; i < 100; i++) {
   
            // 匿名内部类+lambda表达式
            new Thread(() -> {
   
                System.out.println(Singleton.getInstance().hashCode());
            }).start();
        }
        // hashCode 都乱了。线程不安全
    }
}

// 懒汉式(线程不安全)
class Singleton{
   
    // 私有构造器
    private Singleton(){
   }

    private static Singleton instance;

    // 懒汉式,当需要时进行加载(调用getInstance()方法)获得实例对象
    // 提供对外公共的 getInstance()
    public static Singleton getInstance(){
   
        if (instance==null){
   
            // 线程睡眠1s进行测试
            try {
   
                Thread.sleep(1);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
            instance = new Singleton();
        }
        return instance;
    }
}

在这里插入图片描述

4. 懒汉式(线程安全,同步方法)

代码实现:

package com.robin.singleton.type4;

public class SingletonTest4 {
   
    public static void main(String[] args) {
   
        // 测试单例模式--懒汉式(线程安全)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例
    }
}

// 单例模式----懒汉式(线程安全)
class Singleton{
   
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){
   }

    private static Singleton instance ;

    // 对外提供一个公共的返回 singleton 实例对象的方法getInstance()
    // 使用同步方法 synchronized 线程同步锁
    public static synchronized Singleton getInstance(){
   
        if (instance==null){
   
            instance = new Singleton();
        }
        return instance;
    }
}

线程测试:

package com.robin.singleton.type4.threadSingleton;

public class TestThreadSingleton {
   
    public static void main(String[] args) {
   
        System.out.println("多线程测试【懒汉式单例模式】");
        for (int i = 0; i < 100; i++) {
   
            new Thread(()->{
   
                System.out.println(Singleton.getInstance().hashCode());
            }).start();
        }
        // 哈希值没有乱,线程安全
        // 但是同步锁 synchronized 比较耗费时间,效率不高
    }
}

// 懒汉式(线程安全)
class Singleton{
   

    // 私有化构造器
    private Singleton(){
   }
    // 静态变量
    private static Singleton instance;
    // 向外提供getInstance()方法,需要时才创建
    // synchronized 线程同步锁
    public static synchronized Singleton getInstance(){
   
        if (instance==null){
   
            // 为了线程测试,线程中断休眠1s
            try {
   
                Thread.sleep(1);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
            instance = new Singleton();
        }
        return instance;
    }
}

在这里插入图片描述

优缺点:

  1. 优点:通过synchronized同步方法解决了多线程的安全问题
  2. 缺点:效率较低,因为同步锁的问题,内次都需要进行锁,无论实例是否存在

实际开发中,不推荐这种使用方式。

5. 懒汉式(线程不安全,同步代码块)

代码实现:

package com.robin.singleton.type5;

public class SingletonTest5 {
   
    public static void main(String[] args) {
   
        // 测试单例模式--懒汉式(线程不安全)
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
        // instance1 与 instance2 哈希值一致,是同一个对象实例
    }
}

// 单例模式----懒汉式(线程不安全,妄图通过减小同步代码块的方式来提高效率)
class Singleton{
   
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){
   }

    private static Singleton instance ;

    // 对外提供一个公共的返回 singleton 实例对象的方法getInstance()
    public static  Singleton getInstance(){
   
        if (instance==null){
   
            // 妄图通过减小同步代码块的方式来提高效率,会导致线程不安全
            synchronized(Singleton.class){
   
                instance = new Singleton();
            }
        }
        return instance;
    }
}

多线程测试:

package com.robin.singleton.type5.threadSingleton;

public class SingletonTest5 {
   
    public static void main(String[] args) {
   
        // 测试单例模式--懒汉式(线程不安全)
        for (int i = 0; i < 100; i++) {
   
            new Thread(()->{
   
                System.out.println(Singleton.getInstance().hashCode());
            }).start();
        }
    }
}

// 单例模式----懒汉式(线程不安全,妄图通过减小同步代码块的方式来提高效率)
class Singleton{
   
    // 私有构造器,防止外部以 new 的方式创建对象
    private Singleton(){
   }

    private static Singleton instance ;

    // 对外提供一个公共的返回 singleton 实例对象的方法getInstance()
    public static  Singleton getInstance(){
   
        if (instance==null){
   
            // 妄图通过减小同步代码块的方式来提高效率,会导致线程不安全
            synchronized(Singleton.class){
   
                // 线程休眠1s
                try {
   
                    Thread.sleep(1);
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
                instance = new Singleton();
            }

        }
        return instance;
    }
}

在这里插入图片描述

妄图通过减小同步代码块的方式来提高效率,但会导致多线程还是存在安全问题,只能在单线程下使用,不推荐使用。

6. 双重检查

通过双重检查保证线程安全,两次 if(singleton==null)。实例化代码只执行一次,避免反复进行方法同步。

代码实现:

package com.robin.singleton.type6;

public class SingletonTest6 {
   
    public static void main(String[] args) {
   
        // 测试单例模式--双重检查
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
    }
}

// 单例模式--双重检查
class Singleton{
   
    private Singleton(){
   };

    // 使用 volatile 关键字
    private static volatile Singleton instance;

    public static Singleton getInstance(){
   
        if (instance==null){
   
            synchronized (Singleton.class){
   
                if (instance==null){
   
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

}

解决了多线程的安全问题,双重检查可以解决懒加载问题,即在使用时才会加载(避免浪费内存资源),同时保证了效率,推荐使用。

7. 静态内部类

静态内部类在使用时才会实例化,避免资源浪费,实现延迟加载。同时JVM保证了线程的安全,在类进行初始化时,只有一个线程才能进入。

代码实现:

package com.robin.singleton.type7;

public class SingletonTest7 {
   
    public static void main(String[] args) {
   
        // 测试单例模式--静态内部类的方式
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println("instance1======"+instance1.hashCode());
        System.out.println("instance2======"+instance2.hashCode());
    }
}

// 单例模式--静态内部类的方式
class Singleton{
   
    private Singleton(){
   };

    // 私有静态内部类
    private static class SingletonInstance{
   
        private static final Singleton INSTANCE =new Singleton();
    }

    // 提供公有的外部获取实例的方法 getInstance()
    public static Singleton getInstance(){
   
        return SingletonInstance.INSTANCE;
    }

}

避免了线程不安全,利用静态内部类的特点实现延迟加载,效率高。

推荐使用+1!

8. 枚举

使用枚举来实现单例模式,既可以避免多线程同步问题,也能防止反序列化重新创建新的对象。推荐使用+1!

代码实现:

package com.robin.singleton.type8;

public class SingletonTest8 {
   
    public static void main(String[] args) {
   
        // 测试单例模式--枚举的方式
        Singleton instance1 = Singleton.INSTANCE;
        Singleton instance2 = Singleton.INSTANCE;
        System.out.println(instance1==instance2);
        System.out.println("instance1===="+instance1.hashCode());
        System.out.println("instance2===="+instance2.hashCode());
    }
}

// 单例模式--枚举的方式
enum Singleton{
   
    INSTANCE;
}

相关文章
|
9天前
|
弹性计算 人工智能 架构师
阿里云携手Altair共拓云上工业仿真新机遇
2024年9月12日,「2024 Altair 技术大会杭州站」成功召开,阿里云弹性计算产品运营与生态负责人何川,与Altair中国技术总监赵阳在会上联合发布了最新的“云上CAE一体机”。
阿里云携手Altair共拓云上工业仿真新机遇
|
6天前
|
机器学习/深度学习 算法 大数据
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
2024“华为杯”数学建模竞赛,对ABCDEF每个题进行详细的分析,涵盖风电场功率优化、WLAN网络吞吐量、磁性元件损耗建模、地理环境问题、高速公路应急车道启用和X射线脉冲星建模等多领域问题,解析了问题类型、专业和技能的需要。
2501 14
【BetterBench博士】2024 “华为杯”第二十一届中国研究生数学建模竞赛 选题分析
|
6天前
|
机器学习/深度学习 算法 数据可视化
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
2024年中国研究生数学建模竞赛C题聚焦磁性元件磁芯损耗建模。题目背景介绍了电能变换技术的发展与应用,强调磁性元件在功率变换器中的重要性。磁芯损耗受多种因素影响,现有模型难以精确预测。题目要求通过数据分析建立高精度磁芯损耗模型。具体任务包括励磁波形分类、修正斯坦麦茨方程、分析影响因素、构建预测模型及优化设计条件。涉及数据预处理、特征提取、机器学习及优化算法等技术。适合电气、材料、计算机等多个专业学生参与。
1517 14
【BetterBench博士】2024年中国研究生数学建模竞赛 C题:数据驱动下磁性元件的磁芯损耗建模 问题分析、数学模型、python 代码
|
8天前
|
编解码 JSON 自然语言处理
通义千问重磅开源Qwen2.5,性能超越Llama
击败Meta,阿里Qwen2.5再登全球开源大模型王座
523 12
|
1月前
|
运维 Cloud Native Devops
一线实战:运维人少,我们从 0 到 1 实践 DevOps 和云原生
上海经证科技有限公司为有效推进软件项目管理和开发工作,选择了阿里云云效作为 DevOps 解决方案。通过云效,实现了从 0 开始,到现在近百个微服务、数百条流水线与应用交付的全面覆盖,有效支撑了敏捷开发流程。
19282 30
|
1月前
|
人工智能 自然语言处理 搜索推荐
阿里云Elasticsearch AI搜索实践
本文介绍了阿里云 Elasticsearch 在AI 搜索方面的技术实践与探索。
18836 20
|
1月前
|
Rust Apache 对象存储
Apache Paimon V0.9最新进展
Apache Paimon V0.9 版本即将发布,此版本带来了多项新特性并解决了关键挑战。Paimon自2022年从Flink社区诞生以来迅速成长,已成为Apache顶级项目,并广泛应用于阿里集团内外的多家企业。
17523 13
Apache Paimon V0.9最新进展
|
8天前
|
人工智能 自动驾驶 机器人
吴泳铭:AI最大的想象力不在手机屏幕,而是改变物理世界
过去22个月,AI发展速度超过任何历史时期,但我们依然还处于AGI变革的早期。生成式AI最大的想象力,绝不是在手机屏幕上做一两个新的超级app,而是接管数字世界,改变物理世界。
452 48
吴泳铭:AI最大的想象力不在手机屏幕,而是改变物理世界
|
22小时前
|
云安全 存储 运维
叮咚!您有一份六大必做安全操作清单,请查收
云安全态势管理(CSPM)开启免费试用
352 4
叮咚!您有一份六大必做安全操作清单,请查收
|
2天前
|
存储 关系型数据库 分布式数据库
GraphRAG:基于PolarDB+通义千问+LangChain的知识图谱+大模型最佳实践
本文介绍了如何使用PolarDB、通义千问和LangChain搭建GraphRAG系统,结合知识图谱和向量检索提升问答质量。通过实例展示了单独使用向量检索和图检索的局限性,并通过图+向量联合搜索增强了问答准确性。PolarDB支持AGE图引擎和pgvector插件,实现图数据和向量数据的统一存储与检索,提升了RAG系统的性能和效果。