作用:保证当前类同时只能有一个对象存在,且这个类必须自行创建这个实例并向系统提供这个实例。

步骤:

  1. 私有化类的构造函数。
  2. 在类中使用new创建一个当前类的对象。
  3. 提供一个公开的方法,将创建的对象返回。饿汉式:
class Single
{
private static final Single Instance=new Single();
private Single(){};
public static Single getInstance()
{
return Instance;
}
}
  1. 懒汉式:
class Single
{
private static final Single Instance;
private Single(){};
public static synchronized Single getInstance()
{
if(null==Instance)
{
Instance=new Single()
}
return Instance;
}
}