设计模式:单例模式singleton示例分析

public class singleton {
	private singleton(){
		System.out.println("构造方法被调用!");
	}
	private  static class  singletonHolder{
		private static singleton instance = new singleton();
	}
	public static singleton getInstance(){
		return singletonHolder.instance;
	}
	public static void main(String[] args) {
		new Thread(new ThreadTest()).start();
	}
	static  class ThreadTest implements Runnable{
		@Override
		public  void run() {
			long beginTime = System.currentTimeMillis();
			for(int i=0;i<100000;i++){
				singleton.getInstance();
			}
			System.out.println("花费时间为:"+(System.currentTimeMillis()-beginTime));
		}
	}
  

	
}

 以上为单例模式的比较经典的实现,使用内部类的实现方式即可以做到延迟加载,也不必使用同步关键字,是一个比较完善的实现。

我以前可能没有注意优化过,一般实现时为了延迟加载我们会使用同步关键字,但是大大降低了性能,经过测试,使用synchronized跟不使用时时间上差两个数量级,但以上这种实现可以性能比较好,当然,以上实现还是不能完全保证只生成一个单例,比如使用反射机制,强行调用私有构造方法,还是能生成多个实例,现不讨论这种极端方式,但还是一些合法的方法,可以导致生成多个单例类的实例。

在进行序列化跟反序列化时可能会导致生成多个实例,如果有这种情况,就要注意,可以避免!

猜你喜欢

转载自xiangyuan.iteye.com/blog/2075465