设计模式--单例模式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;
    }
}
AI 代码解读

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;
    }
}
AI 代码解读

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;
    }
}
AI 代码解读

多线程测试:

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;
    }
}
AI 代码解读

在这里插入图片描述

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;
    }
}
AI 代码解读

线程测试:

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;
    }
}
AI 代码解读

在这里插入图片描述

优缺点:

  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;
    }
}
AI 代码解读

多线程测试:

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;
    }
}
AI 代码解读

在这里插入图片描述

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

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;
    }

}
AI 代码解读

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

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;
    }

}
AI 代码解读

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

推荐使用+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;
}
AI 代码解读

目录
打赏
0
0
0
0
83
分享
相关文章
【设计模式】【创建型模式】单例模式(Singleton)
一、入门 什么是单例模式? 单例模式是一种设计模式,确保一个类只有一个实例,并提供一个全局访问点。它常用于需要全局唯一对象的场景,如配置管理、连接池等。 为什么要单例模式? 节省资源 场景:某些对象创
123 15
设计模式-单例模式练习
单例模式是Java设计模式中的重要概念,确保一个类只有一个实例并提供全局访问点。本文详解单例模式的核心思想、实现方式及线程安全问题,包括基础实现(双重检查锁)、懒汉式与饿汉式对比,以及枚举实现的优势。通过代码示例和类图,深入探讨不同场景下的单例应用,如线程安全、防止反射攻击和序列化破坏等,展示枚举实现的简洁与可靠性。
77 0
设计模式:单例模式
单例模式是一种创建型设计模式,确保一个类只有一个实例,并提供全局访问点。它通过私有化构造函数、自行创建实例和静态方法(如`getInstance()`)实现。适用于数据库连接池、日志管理器等需要全局唯一对象的场景。常见的实现方式包括饿汉式、懒汉式、双重检查锁、静态内部类和枚举。线程安全问题可通过`synchronized`或双重检查锁解决,同时需防止反射和序列化破坏单例。优点是避免资源浪费,缺点是可能增加代码耦合度和测试难度。实际开发中应优先选择枚举或静态内部类,避免滥用单例,并结合依赖注入框架优化使用。
设计模式2:单例模式
单例模式是一种创建型模式,确保一个类只有一个实例,并提供全局访问点。分为懒汉式和饿汉式: - **懒汉式**:延迟加载,首次调用时创建实例,线程安全通过双重检查锁(double check locking)实现,使用`volatile`防止指令重排序。 - **饿汉式**:类加载时即创建实例,线程安全但可能浪费内存。 示例代码展示了如何使用Java实现这两种模式。
61 4
前端必须掌握的设计模式——单例模式
单例模式是一种简单的创建型设计模式,确保一个类只有一个实例,并提供一个全局访问点。适用于窗口对象、登录弹窗等场景,优点包括易于维护、访问和低消耗,但也有安全隐患、可能形成巨石对象及扩展性差等缺点。文中展示了JavaScript和TypeScript的实现方法。
168 13
Kotlin教程笔记(57) - 改良设计模式 - 单例模式
Kotlin教程笔记(57) - 改良设计模式 - 单例模式
87 2
Java编程中的设计模式:单例模式的深度剖析
【10月更文挑战第41天】本文深入探讨了Java中广泛使用的单例设计模式,旨在通过简明扼要的语言和实际示例,帮助读者理解其核心原理和应用。文章将介绍单例模式的重要性、实现方式以及在实际应用中如何优雅地处理多线程问题。
111 4
Kotlin教程笔记(57) - 改良设计模式 - 单例模式
Kotlin教程笔记(57) - 改良设计模式 - 单例模式
Kotlin教程笔记(57) - 改良设计模式 - 单例模式
Kotlin教程笔记(57) - 改良设计模式 - 单例模式
Kotlin教程笔记(57) - 改良设计模式 - 单例模式
Kotlin教程笔记(57) - 改良设计模式 - 单例模式
64 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问