单例设计模式 饿汉式 懒汉式

单例设计模式

设计模式:对问题行之有效的解决方式。其实它是一种思想。

1,单例设计模式。
解决的问题:就是可以保证一个类在内存中的对象唯一性

必须对于多个程序使用同一个配置信息对象时,就需要保证该对象的唯一性。

如何保证对象唯一性呢?
1,不允许其他程序用new创建该类对象。
2,在该类创建一个本类实例。
3,对外提供一个方法让其他程序可以获取该对象。


class Single//类一加载,对象就已经存在了。
{
	private static Single s = new Single();

	private Single(){}

	public static Single getInstance()
	{
		return s;
	}
}



步骤:
1,私有化该类构造函数。
2,通过new在本类中创建一个本类对象。
3,定义一个公有的方法,将创建的对象返回。

class Single
{
	private Single (){};	//有化该类构造函数。
	private static Single s= new Single();	//通过new在本类中创建一个本类对象。
	public static Single getInstance()
	{
		return s;//定义一个公有的方法,将创建的对象返回。
	}

}

class SingleDemo
{
	public static void main(String [] args)
	{
		Single s1=Single.getInstance();
		Single s2=Single.getInstance();
			
		System.out.println(s1==s2);
	}
}

饿汉式   懒汉式
//饿汉式
class Single//类一加载,对象就已经存在了。
{
	private static Single s = new Single();

	private Single(){}

	public static Single getInstance()
	{
		return s;
	}
}

//懒汉式
class Single2//类加载进来,没有对象,只有调用了getInstance方法时,才会创建对象。
			//延迟加载形式。 
{
	private static Single2 s = null;

	private Single2(){}

	public static Single2 getInstance()
	{
		if(s==null)
			s = new Single2();
		return s;
	}
}
class  SingleDemo
{
	public static void main(String[] args) 
	{
		Single s1 = Single.getInstance();
		Single s2 = Single.getInstance();

		System.out.println(s1==s2);


单例设计模式--懒汉式 线程同步。。

class Single
{
	private static Single s = null;
	private Single(){};
	public static Single getInstance()
	{
		if(s==null)
		{
			synchronized (Single.class)
			{
				if (s==null)
				s= new Single();
			}
		}
		return s;
	}
}
class SingleDemo
{
	public static void main(String [] args)
	{
		Single s1=Single.getInstance();
		Single s2=Single.getInstance();
			
		System.out.println(s1==s2);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值