1、创建一个类将无参构造器变成私有权限(有两种实现方式)
点击查看代码
package com.bh.test;
public class Person {
//(2)
//private static Person person;
//将person变量定义成静态变量,因为getInstance()为静态方法只能调用静态变量
private static Person person = new Person();
private String name;
private Person(){}
//将构造器私有化后只能本类调用,所以通过一个public方法来调用构造器实现创建对象,别的类只需要调用这个方法就行,又因为别的类不能创建对象所以方法变成static修饰的静态,只需要类名.方法就行
public static Person getInstance(){
/*(2)
Person p = new Person();
if (person == null){
person = new Person();
}*/
return person;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
点击查看代码
package com.bh.test;
public class Test {
public static void main(String[] args) {
Person p1 = Person.getInstance();
Person p2 = Person.getInstance();
Person p3 = Person.getInstance();
System.out.println(p1.getName());
System.out.println(p2.getName());
System.out.println(p3.getName());
}
}