一概念:
设计模式:设计模式是指经过大量的实践总结和理论化之后的优选的代码结构、编程风格、以及解决问题的思路。
单态设计模式:采取一定的方法保证在整个软件系统中,对某个类只能产生一个对象实例,并且该类只提供一个取得其对象的实例方法。
二实现:
在java中实现单态模式只需要执行以下三步:
1.将构造函数声明为private。这样就只能在该类的内部生成对象,而不能在外部通过new来产生对象。
2.在类内部生成一个静态的实例。
3.提供一个静态的方法用于外部取得该类的实例。
三举例:
class Chinese
{
static Chinese chinese = new Chinese();
private Chinese()
{
}
public static Chinese getInstance()
{
return chinese;
}
}
改进:
class Chinese
{
static Chinese chinese = null;
private Chinese()
{
}
public static Chinese getInstance()
{
if( chinese == null)
chinese = new Chinese();
return chinese;
}
}