高效懒汉模式

public class Person {

	// 1、将构造方法私有化,防止外界创建对象
	private Person(){ super(); }
	
	/ /2、创建自己的对象
	private static Person person;

	// 3、给外界访问方式,双重锁,保证线程安全的同时保障方法执行效率
	public static Person getInstance(){
		if(person==null){
			synchronized (Person.class){
				if(person==null){
					person=new Person();
				}
			}
		}
		//如果之前创建过,直接使用之前的对象
		return person;
	}
}
发布了34 篇原创文章 · 获赞 1 · 访问量 527

猜你喜欢

转载自blog.csdn.net/weixin_42440154/article/details/103281627