设计模式

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

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

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

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

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

//饿汉式
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 Test
{
	private int num;
	private static Test t = new Test();
	private Test() {}
	public static Test getinstance()
	{
		return t;
	}
	public void setnum (int num)
	{
		this.num = num;
		
	}
	public int getnum( ) 
	{
		return num;
	}

  static class singleDemo
{
	public static void main (String[] args) 
	{
		single s1 = single.getinstance();
		single s2 = single.getinstance();
		
		System.out.println(s1 == s2);
	
		
		
		Test t1 = Test.getinstance();
		Test t2 = Test.getinstance();
		
		t1.setnum(10);
		t2.setnum(90);
		
		System.out.println(t1.getnum());
		System.out.println(t2.getnum());
		
	}
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值