·单例类
单实例类,就是这个类只能创建一个对象。
例子:单实例类
class Singleton
{
private static Singleton instance; //使用static修饰,因为它要在该类的静态方法中被访问,作用 //是一个引用变量指向对象。
private Singleton(){}; //提供一个私有的构造器,使用方法来控制它创建对象的个数。
//方法必须是public的和static的,因为方法要公开被下面的类调用并且下面的s1引用变量获取方法的方式是 //通过类.方法来实现的。因为不能创建对象,所以只能用类。这样就约束了只能创建一个对象。
public static Singleton getInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
public class SingletonTest
{
public static void main(String[] args)
{
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2); //这里可以看出确实是同一个对象
}
}