面试相关:单例模式实现的N种方式

mac2024-04-04  61

(1)只适合单线程环境(不好)

缺点:只在单线程的情况下正常运行,在多线程的情况下,就会出问题。例如:当两个线程同时运行到判断instance是否为空的if语句,并且instance确实没有创建好时,那么两个线程都会创建一个实例。

package com.disruptor.demo.test; /** * 单例模式 * @author 零落尘土 * */ public class Singleton { private static Singleton instance = null; private Singleton() { } //(1)只适合单线程的方式 public static Singleton getIntance() { if(instance == null) { instance = new Singleton(); } return instance; } }

(2)适合多线程的方式,加上了同步锁的方式

缺点:每次通过getInstance方法得到singleton实例的时候都有一个试图去获取同步锁的过程。而众所周知,加锁是很耗时的。能避免则避免。

package com.disruptor.demo.test; /** * 单例模式 * @author 零落尘土 * */ public class Singleton { private static Singleton instance = null; private Singleton() { } //(2)适合多线程的方式,加上了同步锁的方式 public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }

(3)加同步锁时候,前后两次判断实例是否存在(可行)

缺点:用双重if判断,复杂,容易出错。

package com.disruptor.demo.test; /** * 单例模式 * @author 零落尘土 * */ public class Singleton { private static Singleton instance = null; private Singleton() { } //(3)加同步锁时候,前后两次判断实例是否存在(可行) public static Singleton getInstance() { if(instance == null) { synchronized(Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; } }

(4)饿汉模式(建议使用)

初始化静态的instance创建一次。如果我们在Singleton类里面写一个静态的方法不需要创建实例,它仍然会早早的创建一次实例。而降低内存的使用率。

缺点:没有lazy loading的效果,从而降低内存的使用率。

package com.disruptor.demo.test; /** * 饿汉式实现单例模式 * @author 零落尘土 * */ public class Singleton1 { private static Singleton1 instance = new Singleton1(); private Singleton1(){ } public static Singleton1 getInstance() { return instance; } }

(5)静态内部内(建议使用)

定义一个私有的内部类,在第一次用这个嵌套类时,会创建一个实例。而类型为SingletonHolder的类,只有在Singleton.getInstance()中调用,由于私有的属性,他人无法使用SingleHolder,不调用Singleton.getInstance()就不会创建实例。 优点:达到了lazy loading的效果,即按需创建实例。

package com.disruptor.demo.test; /** * 静态内部内 * @author 零落尘土 * */ public class Singleton2 { private Singleton2() { } private static class SingletonHolder{ private final static Singleton2 instance = new Singleton2(); } public static Singleton2 getInstance() { return SingletonHolder.instance; } }

 

参考 https://www.jianshu.com/p/1acdfac2b4e4

 

 

 

 

 

最新回复(0)