Singleton模式是java中用到最多的设计模式。用于控制的个数,防止多余的实例化及修改。在仅有一个对象存在时,操作很有效。
1、构造函数私有化,其它类不能实例化对象
2、引用私有化,没有其它的修改
3、公有的静态方法唯一获取对象
第一种实现:
class AmericanPresident
{
private static final AmericanPresident thePresident = new AmericanPresident();
private AmericanPresident() {}
public static AmericanPresident getPresident()
{
return thePresident;
}
}
第二种实现:
class AmericanPresident
{
private static AmericanPresident thePresident ;
private AmericanPresident() {}
public static AmericanPresident getPresident()
{
if (thePresident == null) thePresident = new AmericanPresident();
return thePresident;
}
}
java标准库中使用singleton模式的有java.lang.Runtime#getRuntime()