保证一个类仅有一个实例,并提供一个访问它的全局访问点。
class Person{
private static Person person;
private Person(){}//将构造函数私有,外界就不会用new来创建对象了
//提供一个访问这个对象的方法
public static Person getInstance(){
if (person == null)
person = new Person();
return person;
}
}
public class Client {
public static void main(String[] args) {
Person p1 = Person.getInstance();
Person p2 = Person.getInstance();
System.out.println(p1 == p2);
System.out.println(p1.equals(p2));
}
}
原文:https://www.cnblogs.com/xxgbl/p/13758716.html