单例模式属于对象创建性质的模式,用于产生一个对象的具体实例,并且可以确保系统中一个类只能产生一个实例。

饥饿式单例

public class Singleton {
	private  static Singleton singleton = new Singleton();
	private Singleton(){
		System.out.println("Singleton is create");
	}
	public static Singleton getInstance(){
		return singleton;
	}
}

懒汉式单例

public class LazySingleton {

	private LazySingleton(){
		System.out.println("LazySingleton is create");
	}
	private static LazySingleton instance = null;
	public static synchronized LazySingleton getInstance(){
		if(instance==null)
			instance = new LazySingleton();
		return instance;
	}
}

内部类式单例

public class StaticSingleton {
	
	private StaticSingleton(){
		System.out.println("Static Singleton is create");
	}
	private static class SingletonHolder{
		private static StaticSingleton instance = new StaticSingleton();
	}
	public static final StaticSingleton getInstance(){
		return SingletonHolder.instance;
	}
}

性能比较

创建5个线程,模拟多线程环境下的性能

public class Client implements Runnable{
	public static void main(String[] args) {
		Client client = new Client();

		new Thread(client).start();
		new Thread(client).start();
		new Thread(client).start();
		new Thread(client).start();
		new Thread(client).start();


	}

	@Override
	public void run() {
		long begintime = System.currentTimeMillis();
		for(int i = 0;i<100000;i++)
			StaticSingleton.getInstance();
		System.out.println("spend:"+(System.currentTimeMillis()-begintime));
	}
}

两次比较

懒汉式 185ms 190ms
饥饿式 54ms 49ms
内部类式 56ms 61ms
在多线程条件下,懒汉式单例耗时要比饥饿式耗时要多很多,因为懒汉式为了使用延迟加载而引入了同步关键字,降低了系统性能
而内部类式单例既可以做到延迟加载,又不必使用同步关键字,是一种比较完善的实现。

双检查的懒汉单例模式

关于作者

后端程序员,五年开发经验,从事互联网金融方向。技术公众号「清泉白石」。如果您在阅读文章时有什么疑问或者发现文章的错误,欢迎在公众号里给我留言。

设计模式(四)—— 单例模式

相关文章:

  • 2021-12-29
  • 2018-02-06
  • 2021-11-17
  • 2022-12-23
  • 2021-09-13
  • 2021-12-15
  • 2021-08-01
  • 2021-12-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-20
  • 2022-12-23
  • 2022-01-21
  • 2021-06-23
  • 2021-05-26
相关资源
相似解决方案