我目前正在学习Java.我有一个带有超类(IndexCard)和两个子类(EmployeeIndexCard和CustomerIndexCard)的项目.这两个子类非常相似,但是它们的实例变量(因此,其构造函数)彼此不同.
他们来了:
class EmployeeIndexCard extends IndexCard {
public WorkArea workArea ;
protected String password;
public employeeIndexCard(String name, String password, String adress, String phone, String email, String workArea) {
super(name, adress, phone, email);
this.password = password;
this.workArea = WorkArea.valueOf(workArea);
}
}
class CustomerIndexCard extends IndexCard {
public customerIndexCard(String name, String adress, String phone, String email) {
super(name, adress, phone, email);
}
}
我想知道我在做什么错,因为要创建这些类的实例,我创建了两个非常相似的方法:
/**
* Create an instance of EmployeeIndexCard.
*/
public static void employeeIndexCard(String name, String dni, String password, String adress, String phone, String email, String workArea) {
if (Utils.validateDni(dni) && !IndexCard.list.containsKey(dni)) {
IndexCard.list.put(dni, new EmployeeIndexCard(name, password, adress, phone, email, workArea));
} else {
throw new InvalidParameterException();
}
}
/**
* Create an instance of CustomerIndexCard.
*/
public static void customerIndexCard(String name, String dni, String adress, String phone, String email) {
if (Utils.validateDni(dni) && !IndexCard.list.containsKey(dni)) {
IndexCard.list.put(dni, new FichaCliente(name, adress, phone, email));
} else {
throw new InvalidParameterException();
}
}
有什么方法可以重组代码以合并几乎相同的后两个方法吗?
解决方法:
由于您的两个类共享一个父类,因此重构代码的最自然的方法是将创建实例的责任交给调用者,并接受IndexCard类型的任何实例:
public static void addIndexCard(String dni, IndexCard indexCard) {
if (Utils.validateDni(dni) && !IndexCard.list.containsKey(dni)) {
IndexCard.list.put(dni, indexCard);
} else {
throw new InvalidParameterException();
}
}
这样,您可以简单地调用它:
//add customer index card:
addIndexCard("dni", new FichaCliente(name, adress, phone, email));
//add employee index card:
addIndexCard("dni2", new EmployeeIndexCard(name, password, adress,
phone, email, workArea));