设计模式之单例


一、什么是单例模式:

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

二、单例模式的实现方式:(7种)

  1.饿汉式(静态变量):

//饿汉式(静态变量)
class Singleton {
    
    //1. 构造器私有化, 外部能new
    private Singleton() { } //2.本类内部创建对象实例 private final static Singleton instance = new Singleton(); //3. 提供一个公有的静态方法,返回实例对象 public static Singleton getInstance() { return instance; } }

    优:写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。 

    缺:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用过这个实例,则会造成内存的浪费。

    评价:这种模式可用,但可能会造成内存浪费

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

class Singleton {
    
    //1. 构造器私有化, 外部能new
    private Singleton() { } //2.本类内部创建对象实例 private static Singleton instance; static { // 在静态代码块中,创建单例对象 instance = new Singleton(); } //3. 提供一个公有的静态方法,返回实例对象 public static Singleton getInstance() { return instance; } }

    与上面类似

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

class Singleton {
    private static Singleton instance; private Singleton() {} //提供一个静态的公有方法,当使用到该方法时,才去创建 instance //即懒汉式 public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }

    优:起到了Lazy Loading的效果 

    缺:多线程环境下不可使用这种方式

    评价:只能在单线程下使用

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

// 懒汉式(线程安全,同步方法)
class Singleton {
    private static Singleton instance; private Singleton() {} //提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题 //即懒汉式 public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }

    优:解决了线程不安全问题

    缺:效率太低了,每个线程在想获得类的实例时候,执行getInstance()方法都要进行 同步

    评价:不推荐使用

  5.双重检查

class Singleton {
    private static volatile Singleton instance; private Singleton() {} //提供一个静态的公有方法,加入双重检查代码,解决线程安全问题, 同时解决懒加载问题 //同时保证了效率, 推荐使用 public static synchronized Singleton getInstance() { if(instance == null) { synchronized (Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; } }

    评价:线程安全;延迟加载;效率较高 ,推荐使用

  6.静态内部类:   

// 静态内部类完成, 推荐使用
class Singleton {
    private static volatile Singleton instance; //构造器私有化 private Singleton() {} //写一个静态内部类,该类中有一个静态属性 Singleton private static class SingletonInstance { private static final Singleton INSTANCE = new Singleton(); } //提供一个静态的公有方法,直接返回SingletonInstance.INSTANCE public static synchronized Singleton getInstance() { return SingletonInstance.INSTANCE; } }

    评价:

  • 静态内部类方式在外部类被装载时并不会立即实例化,而是在需要实例化 时,才会装载内部类,从而完成内部的 实例化。
  • 类的静态属性只会在第一次加载类的时候初始化,所以在这里,JVM帮助我们保证了线程的安全性,在类进行初始化时,别的线程是无法进入的。
  • 避免了线程不安全,利用静态内部类特点实现延迟加载,效率高,推荐使用

  7.枚举类

public class SingletonTest08 {
    public static void main(String[] args) { Singleton instance = Singleton.INSTANCE; Singleton instance2 = Singleton.INSTANCE; System.out.println(instance == instance2); } } //使用枚举,可以实现单例, 推荐 enum Singleton { INSTANCE; //属性 public void sayOK() { System.out.println("ok~"); } }

    评价:借助JDK1.5中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而 且还能防止反序列化重新创建新的对象,推荐使用

  8.线程池

 

public class Singleton {
    
    private Singleton() {} private static final ThreadLocal<Singleton> tlSingleton = new ThreadLocal<Singleton>() { @Override protected Singleton initialValue() { return new Singleton(); } }; public static Singleton getInstance() { return tlSingleton.get(); } } 

  9.CAS

public class Singleton {

    /**利用AtomicReference */
    private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>(); private Singleton(){} //用CAS确保线程安全 public static final Singleton getInstance(){ for (;;) { Singleton current = INSTANCE.get(); if (null != current) { return current; } current = new Singleton(); if (INSTANCE.compareAndSet(null, current)) { return current; } } } public static void main(String[] args) { Singleton singleton1 = Singleton.getInstance(); Singleton singleton2 = Singleton.getInstance(); System.out.println(singleton1 == singleton2); } } 

 

 

三、单例模式的jdk使用:  

package java.lang;
 
import java.io.*; import java.util.StringTokenizer; public class Runtime {//这里使用了饿汉式,因为runtime肯定会用到,不会浪费资源 private static Runtime currentRuntime = new Runtime(); public static Runtime getRuntime() { return currentRuntime; } /** Don't let anyone else instantiate this class */ private Runtime() {}

 

四、一些常见问题:https://blog.csdn.net/qq_40868987/article/details/103266261

  1.静态类和单例的区别:

单例可以继承和被继承,方法可以被override,而静态方法不可以。

静态方法中产生的对象会在执行后被释放,进而被GC清理,不会一直存在于内存中。

静态类会在第一次运行时初始化,单例模式可以有其他的选择,即可以延迟加载。

静态方法如果反复的初始化和释放,则会占用很多资源,而使用单例模式将其常驻于内存可以更加节约资源。

静态方法有更高的访问效率。

单例模式很容易被测试。

  2.序列化和反序列化会破坏单例吗?

     会,解决方案:

  (1)https://blog.csdn.net/weixin_34087301/article/details/91400619

  (2)https://www.cnblogs.com/chiclee/p/9097772.html

  3.线程池的单例实现:

  https://www.cnblogs.com/zhuangyan728/p/6706746.html

  https://mp.weixin.qq.com/s?src=11&timestamp=1586451635&ver=2268&signature=UhZ9OtKUNP-KVVt8s2q8t0MlH4P5Rts5d0hDebj9u0IWlovSgkG0bM8AQ-oLvRFXjkj8CdeTHSLLyedvrK5aMOfYd*U2mzXxINoDzykwmsI-jC1xJ5gNx*SLFWOJz0ys&new=1


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM