根据不同的调用产生不同的对象。
特点:构造方法私有化,调用static方法返回不同的对象
package ch3;
class People {
private String sex ;
private static final People MAN = new People("男");
private static final People WOMAN = new People("女");
private People(String sex) {
this.sex = sex ;
}
public static People getInstance(int flag) {
switch (flag) {
case 1:
return MAN ;
case 2:
return WOMAN ;
default:
return null ;
}
}
@Override
public String toString() {
return "People [sex=" + sex + "]";
}
}
public class Test{
public static void main(String[] args) {
People people1 = People.getInstance(1);
People people2 = People.getInstance(2);
System.out.println(people1);
System.out.println(people2);
}
}
结果:
People [sex=男]
People [sex=女]