run_wind

导航

黑马程序员——JAVA基础之单列设计模式

------- android培训java培训、期待与您交流! ----------

 

单列设计模式是面试中的一个常考的点,所谓单例模式就是说对象在内存中只能存在一个。如果有其他变量是该类对象,那么他们指向的是同一对象。

 

单列设计模式分为两种,常用饿汉式,常考懒汉式。

 

//单例设计模式之饿汉式,先初始化对象
class Single
{
	private Single(){};//私有构造函数,使函数不能创建对象
	private static Single s = new Single();//静态只能访问静态
	
	public static Single getInstance()//因为不能创建对象,所以只能通过类名调用,所以要静态
	{
		return s;
	}
}

 


 

//这是懒汉式,调用时才创建对象
class Single
{
	private Single(){};//私有构造函数,使外界不能创建对象
	private static Single s = null;//静态只能访问静态
	
	public static Single getIntance()//因为不能创建对象,所以只能通过类名调用,所以要静态

	{
		if (s == null)
			s = new Single();

		return s
	}
}


 

 因为懒汉式涉及多线程的一个常考点,所以有下例程序:加双重锁,第一重为了提高效率,第二重为了程序的安全性。

 

//单例设计模式之懒汉式,应用才初始化对象,也叫延时加载
class Single
{
	private Single(){};
	private static Single s = null;
	
	public static Singele getInstance()
	{
		if(s==null)
		{
			synchronized(Single.class)
			{
				if(s==null)
				{
					s = new Single();
				}
			}
		}
		return s;
	}
}


 

------- android培训java培训、期待与您交流! ----------

 

 

 

 

 

posted on 2014-11-25 21:54  run_wind  阅读(270)  评论(0编辑  收藏  举报