黑马程序员--java 单例设计模式

<div><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">单例设计模式解决的问题:保证一个类在内存中的对象唯一性。</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">比如:多程序读取一个配置文件时,建议配置文件封装成对象会方便操作其中数据。但需要保证多个程序读到的是同一个配置文件对象,该配置文件对象在内存中是唯一的。</span></div><div><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">如何保证对象唯一性呢?</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">思想以及步骤:</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">1,不让其他程序创建该类对象。>>></span><span style="font-family:Arial;font-size:14px;color:#ff00;line-height: 26px;">◆私有化构造函数;</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">2,在本类中创建一个本类对象。 >>></span><span style="font-family:Arial;font-size:14px;color:#ff00;line-height: 26px;">◆私有并静态的本类对象;</span><br style="color: rgb(51, 51, 51); line-height: 26px; font-family: Arial; font-size: 14px;" /><span style="font-family:Arial;font-size:14px;color:#333333;line-height: 26px;">3,对外提供方法,让其他程序可以获取这个对象。 >>></span><span style="font-family:Arial;font-size:14px;color:#ff00;line-height: 26px;">◆定义公有并静态的方法,返回该对象。</span></div>
 <pre class="java" name="code">class Single
{
	private Single(){} //私有化构造函数,不让其他程序创建该类实例。   
	private static Single s = new Single(); //创建私有并静态的本类对象。   
	public static Single getInstance()  //定义公有并静态的方法,返回该对象。
	{        
		return s;      
	}  
}   
class Testt
{  
	public static void main(String[] args)
		{     
			Single s1 = Single.getInstance();       
			Single s2 = Single.getInstance();       
			System.out.println(s1==s2);//验证两个对象时不是同一个?true,   
		}  
}


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值