设计模式之单例模式

单例模式

保证一个类仅有一个实例,并提供一个访问它的全局访问点。


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));
    }
}
posted @ 2020-10-01 18:35  xxgbl  阅读(93)  评论(0)    收藏  举报