单例模式

概述

使用单例模式的类,在执行过程中,可以保证其只有一个实例,也就是在其内部对其进行实例化。并使得其构造函数为private,以此来保证不能在外部对其实例化,只能通过调用内部static类型的实例化方法来获取实例。

懒汉式

饿汉式模式是指类一加载就会实例化对象

public class Test {
	public static void main(String[] args) {
		Test2 t = Test2.getInstance();
	}
}

class Test2{
	private static Test2 test = new Test2();
	
	private Test2() {
		System.out.println("对象实例化了");
	}
	
	public static Test2 getInstance() {
		System.out.println("获取到实例");
		return test;
	}
}
/*
 * 结果:
 *  对象实例化了
 *	获取到实例
 */

饿汉式

懒汉式是指在调用getInstance方法时才会实例化对象,不调用则不实例化

public class Test {
	public static void main(String[] args) {
		/*只进行一次实例化*/
		Test2 test = Test2.getInstance();
		Test2 test1 = Test2.getInstance();
		System.out.println(test.equals(test1));
	}
}

class Test2{
	
	private static Test2 test = null;
	
	private Test2() {}
	
	public static Test2 getInstance() {
		if(test ==null) {
			System.out.println("实例化对象了");
			test = new Test2();
		}
		return test;
	}
}
/*
 * 结果:
 *  实例化对象了
 *	true
 */

两者比较

1、空间和时间方面
饿汉式节约了时间但占用了空间,因为类一加载就实例化对象,占用栈中的空间,但是节约了时间。
懒汉式正好相反,在调用类中getInsatance方法时才实例化对象,因此节约了空间,但调用时才创建对象所以浪费了时间。
2、线程安全方面
懒汉式存在线程安全问题,因为当两个线程同时需要得到目标实例时, 有可能对if(single==null)判断同时为true。因而产生线程安全问题。若要解决安全问题,可在懒汉式中加入synchronized。饿汉式因为一加载就实例化对象,因此不存在线程安全问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值