设计模式 —— 单例模式

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

饥饿式单例

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

参考文档

从王者荣耀看设计模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值