设计模式(三)--创建型模式:单例模式

本文详细介绍了Java中实现单例设计模式的八种方式,包括饿汉式、懒汉式、双重检查锁等,分析了每种方式的优缺点和线程安全性,以及在JDK中的应用和注意事项。
摘要由CSDN通过智能技术生成

一、单例设计模式介绍

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

比如 Hibernate 的 SessionFactory,它充当数据存储源的代理,并负责创建 Session 对象SessionFactory 并不是 轻量级的,一般情况下,一个项目通常只需要一个 SessionFactory 就够,这是就会使用到单例模式。

二、单例设计模式八种方式

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

三、八种方式的具体实现

3.1.饿汉式(静态常量)

实现步骤
  • 1.构造器私有化,外部类不能new创建实例
  • 2.类内部创建对象实例(类加载就创建实例,一上来就创建)

类的静态变量在内存中只有一个,java虚拟机在加载类的过程中为静态变量分配内存,静态变量位于方法区,被类的所有实例共享。静态变量可以直接通过类名进行访问,其生命周期取决于类的生命周期。

  • 3.只暴露一个public方法getInstance()获取单例
public class Singleton {
    public static void main(String[] args) {

        SingletonTest instance = SingletonTest.getInstance();
        SingletonTest instance2 = SingletonTest.getInstance();
        System.out.println(instance == instance2); // true
        System.out.println("instance.hashCode=" + instance.hashCode());
        System.out.println("instance2.hashCode=" + instance2.hashCode());
        
    }

}

class SingletonTest {

    // 1.构造器私有化,外部类不能new创建实例
    private SingletonTest() {
    }

    // 2.类内部创建对象实例(类加载就创建实例,一上来就创建)
    private final static SingletonTest instance = new SingletonTest();

    // 3.只暴露一个public方法getInstance()获取单例
    public static SingletonTest getInstance() {
        return instance;
    }
}
输出:
true
instance.hashCode=166239592
instance2.hashCode=166239592
总结
  • 1、优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
  • 2、缺点:在类装载的时候就完成实例化,没有达到 Lazy Loading 的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。
  • 3、这种方式基于 classloder 机制避免了多线程的同步问题,不过,instance 在类装载时就实例化,在单例模式中大多数都是调用 getInstance 方法,但是导致类装载的原因有很多种,因此不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化 instance 就没有达到 lazy loading 的效果 。
  • 4、 结论:这种单例模式可用,可能造成内存浪费。

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

实现步骤
  • 1.构造器私有化,外部类不能new创建实例
  • 2.类内部定义对象实例

使用静态代码块给定义实例创建对象(类加载就会执行静态代码块的代码)

  • 3.只暴露一个public方法getInstance()获取单例
public class Singleton {
    public static void main(String[] args) {

        SingletonTest instance = SingletonTest.getInstance();
        SingletonTest instance2 = SingletonTest.getInstance();
        System.out.println(instance == instance2); // true
        System.out.println("instance.hashCode=" + instance.hashCode());
        System.out.println("instance2.hashCode=" + instance2.hashCode());

    }

}

class SingletonTest {

    // 1.构造器私有化,外部类不能new创建实例
    private SingletonTest() {
    }

    // 2.类内部创建对象实例(静态代码块中创建单例对象(类加载就会执行静态代码块的代码,一上来就创建))
    private final static SingletonTest instance;

    static {
        instance = new SingletonTest();
    }

    // 3.只暴露一个public方法getInstance()获取单例
    public static SingletonTest getInstance() {
        return instance;
    }
}
输出:
true
instance.hashCode=166239592
instance2.hashCode=166239592
总结
  • 这种方式和上面的方式其实类似,只不过将类实例化的过程放在了静态代码块中,也是在类装载的时候,就执 行静态代码块中的代码,初始化类的实例。优缺点和上面是一样的。
  • 结论:这种单例模式可用,但是可能造成内存浪费。

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

实现步骤
  • 1.构造器私有化,外部类不能new创建实例
  • 2.定义实例
  • 3.只暴露一个public方法getInstance()创建单例,使用的时候才创建,所以叫懒汉式
public class Singleton {
    public static void main(String[] args) {

        SingletonTest instance = SingletonTest.getInstance();
        SingletonTest instance2 = SingletonTest.getInstance();
        System.out.println(instance == instance2); // true
        System.out.println("instance.hashCode=" + instance.hashCode());
        System.out.println("instance2.hashCode=" + instance2.hashCode());

    }

}

class SingletonTest {

    // 1.构造器私有化,外部类不能new创建实例
    private SingletonTest() {
    }

    // 2.定义实例
    private static SingletonTest instance;
    
    // 3.只暴露一个public方法getInstance()获取单例
    public static SingletonTest getInstance() {
        if (instance == null){
            instance = new SingletonTest();
        }

        return instance;
    }
}
总结
  • 优点:懒加载Lazy Loading,节约内存。
  • 缺点:只能在单线程下使用,有线程安全问题。
  • t1线程进入了 if (instance == null),但是还未来得及new Singleton();另一个线程t2也通过了if的判断,那么则会创建两个实例。
  • 总结:实际开发不推荐使用。

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

实现步骤
  • 1.构造器私有化,外部类不能new创建实例
  • 2.定义实例
  • 3.只暴露一个的public方法getInstance()创建单例,使用的时候才创建所以叫懒汉式

方法加锁synchronized保证线程安全

public class Singleton {
    public static void main(String[] args) {

        SingletonTest instance = SingletonTest.getInstance();
        SingletonTest instance2 = SingletonTest.getInstance();
        System.out.println(instance == instance2); // true
        System.out.println("instance.hashCode=" + instance.hashCode());
        System.out.println("instance2.hashCode=" + instance2.hashCode());

    }

}

class SingletonTest {

    // 1.构造器私有化,外部类不能new创建实例
    private SingletonTest() {
    }

    // 2.定义实例
    private static SingletonTest instance;

    // 3.只暴露一个public方法getInstance()获取单例
    public static synchronized SingletonTest getInstance() {
        if (instance == null){
            instance = new SingletonTest();
        }

        return instance;
    }
}
输出:
true
instance.hashCode=166239592
instance2.hashCode=166239592
总结
  • 优点:懒加载Lazy Loading,节约内存,加锁后也没有线程安全问题。
  • 缺点:效率过低,getInstance()这个操作是经常发生的,每次操作都要进行同步,我们想要的效果是第一次实例化加锁就行了,后面想要获取实例,直接return即可。
  • 总结:实际开发不推荐使用。

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

实现步骤
  • 1.构造器私有化,外部类不能new创建实例
  • 2.定义实例
  • 3.只暴露一个的public方法getInstance()创建单例,使用的时候才创建所以叫懒汉式

if (instance == null)同时加入两个线程就造成线程安全问题

public class Singleton {
    public static void main(String[] args) {

        SingletonTest instance = SingletonTest.getInstance();
        SingletonTest instance2 = SingletonTest.getInstance();
        System.out.println(instance == instance2); // true
        System.out.println("instance.hashCode=" + instance.hashCode());
        System.out.println("instance2.hashCode=" + instance2.hashCode());

    }

}

class SingletonTest {

    // 1.构造器私有化,外部类不能new创建实例
    private SingletonTest() {
    }

    // 2.定义实例
    private static SingletonTest instance;

    // 3.只暴露一个public方法getInstance()获取单例
    public static  SingletonTest getInstance() {
        if (instance == null){
            synchronized(SingletonTest.class){
                instance = new SingletonTest();
            }
        }

        return instance;
    }
}
总结
  • 优点:懒加载Lazy Loading,节约内存。
  • 缺点:同步代码块再次引发类似方法3的线程不安全问题。
  • 总结:实际开发不推荐使用。

3.6.双重检查锁

实现步骤
  • 1.构造器私有化,外部类不能new创建实例。
  • 2.定义volatile的实例。
  • 3.只暴露一个的public方法getInstance()创建单例,使用的时候才创建所以叫懒汉式。

双重检查锁 = 线程安全 + lazy

public class Singleton {
    public static void main(String[] args) {

        SingletonTest instance = SingletonTest.getInstance();
        SingletonTest instance2 = SingletonTest.getInstance();
        System.out.println(instance == instance2); // true
        System.out.println("instance.hashCode=" + instance.hashCode());
        System.out.println("instance2.hashCode=" + instance2.hashCode());

    }

}

class SingletonTest {

    // 1.构造器私有化,外部类不能new创建实例
    private SingletonTest() {
    }

    // 2.定义实例
    private static volatile SingletonTest instance;

    // 3.只暴露一个public方法getInstance()获取单例
    public static  SingletonTest getInstance() {
        if (instance == null){
            synchronized(SingletonTest.class){
                if (instance == null) {
                    instance = new SingletonTest();
                }
            }
        }

        return instance;
    }
}
输出:
true
instance.hashCode=166239592
instance2.hashCode=166239592
总结
  • 优点:双重检查锁 + volatile 保证了线程安全和懒加载,同时第二次访问判断的时候if(instance == null)不成立是可以直接返回的,并不用加锁判断导致的效率低下。
  • 总结:推荐使用。
  • 如果不用volatile,会出现异常。

(1)instance = new Singleton()这不是一个原子操作
(2)OS会编译为3个指令(A1,分配对象内存空间 A2,初始化对象 A3,设置instance指向堆内存对象)
(3)但是如果3个指令给CPU优化重排序了,A1,A3,A2,那么A3之后直接返回的是没有初始化的instance
(4)volatile只能保证缓存导致可见性,指令重排导致的有序性,但是无法保证原子性,还是的靠大哥synchronized
(5)synchronized能保证原子,可见,有序,但是注意外面的if判断的instance不在加锁的范围内,不受监管!!!

3.7.静态内部类

实现步骤

类加载时,静态内部类是不会被加载的,用到静态内部类的静态变量instance时,才会加载静态内部类,类加载时线程安全的。

  • 1.构造器私有化,外部类不能new创建实例
  • 2.静态内部类创建instance(没调用时不会创建instance)
  • 3.只暴露一个public方法getInstance()创建单例,使用的时候才创建,所以叫懒汉
public class Singleton {
    public static void main(String[] args) {

        SingletonTest instance = SingletonTest.getInstance();
        SingletonTest instance2 = SingletonTest.getInstance();
        System.out.println(instance == instance2); // true
        System.out.println("instance.hashCode=" + instance.hashCode());
        System.out.println("instance2.hashCode=" + instance2.hashCode());

    }

}

class SingletonTest {

    // 1.构造器私有化,外部类不能new创建实例
    private SingletonTest() {
    }

    //写一个静态内部类,该类中有一个静态属性

    private static class SingletonInstance {
        private static final SingletonTest instance = new SingletonTest();
    }

    // 3.只暴露一个public方法getInstance()获取单例
    public static SingletonTest getInstance() {
        return SingletonInstance.instance;
    }
}
总结
  • 保证懒加载:静态内部类一开始是不会加载的,只有调用getInstance()方法,才会加载inner类,从而完成对instance的实例。
  • 保证线程安全:静态属性只会在第一次加载类时初始化,JVM保证了线程安全性(类初始化别的线程是无法进入的)。
  • 总结:延迟加载,效率高,线程安全,推荐使用。

3.8.枚举

实现步骤
  • 相当于静态内部类
  • 单元素的枚举类型已经成为实现Singleton的最佳方法
public class Singleton {
    public static void main(String[] args) {

        SingletonTest instance = SingletonTest.INSTANCE;
        SingletonTest instance2 = SingletonTest.INSTANCE;
        System.out.println(instance == instance2);
        System.out.println(instance.hashCode());
        System.out.println(instance2.hashCode());
        instance.sayOK();
    }

}

//使用枚举,可以实现单例, 推荐
enum SingletonTest {

    INSTANCE; //属性

    public void sayOK() {
        System.out.println("ok~");
    }
}
总结
  • 这借助 JDK1.5 中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而且还能防止反序列化重新创建 新的对象。
  • 这种方式是 Effective Java 作者 Josh Bloch 提倡的方式 。
  • 结论:推荐使用。

四.单例模式在 JDK 应用的源码分析

  • 1、我们 JDK 中,java.lang.Runtime 就是经典的单例模式(饿汉式)。
  • 2、 代码分析+Debug 源码+代码说明。
    在这里插入图片描述

五、单例模式注意事项和细节说明

  • 1、单例模式保证了系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使 用单例模式可以提高系统性能。
  • 2 、当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用 new
  • 3、单例模式使用的场景:需要频繁的进行创建和销毁的对象、创建对象时耗时过多或耗费资源过多(即:重量级 对象),但又经常用到的对象、工具类对象、频繁访问数据库或文件的对象(比如数据源、session 工厂等)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值