Replace Subclass with Fields
2017-08-03 本文已影响15人
坚持编程_lyz
你的各个子类的唯一差别只在 "返回常量数据" 的函数身上.
修改这些函数,使他们返回超类中的某个字段,然后销毁子类;
如果子类没有其他的行为函数,就应该去掉这个继承体系;太简单了,没必要使用继承;
public class Person {
// abstract boolean isMale();
// abstract char getCode();
private final boolean isMale;
private final char getCode;
protected Person(boolean male, char code) {
isMale = male;
getCode = code;
}
public boolean isMale() {
return isMale;
}
public char getCode() {
return getCode;
}
static Person createMale() {
return new Person(true, 'M');
}
static Person createFemale() {
return new Person(false, 'F');
}
public static void main(String[] args) {
Person male = Person.createMale();
Person female = Person.createFemale();
char maleCode = male.getCode();
System.out.println(maleCode);
boolean maleMale = male.isMale();
System.out.println(maleMale);
char femaleCode = female.getCode();
System.out.println(femaleCode);
boolean femaleMale = female.isMale();
System.out.println(femaleMale);
}
}
/*class Male extends Person {
Male() {
super(true, 'M');
}
// @Override
// boolean isMale() {
// return true;
// }
// @Override
// char getCode() {
// return 'M';
// }
}*/
/*class Female extends Person {
Female() {
super(false, 'F');
}
// @Override
// boolean isMale() {
// return false;
// }
// @Override
// char getCode() {
// return 'F';
// }
}*/