我目前正在学习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();
}
}
有没有办法重构代码以合并这两个几乎完全相同的方法?
答案 0 :(得分:2)
由于您的两个类共享一个父类,因此重构代码的最自然方式是负责为调用者创建实例,并接受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));
答案 1 :(得分:1)
从我的角度来看,问题是你在这里反对面向对象的设计。您没有提供对IndexCard
类的访问权限,但它看起来应该是这样的:
public class IndexCard {
public static Map<String, IndexCard> map = new HashMap<>();
private String name;
private String address;
private String phone;
private String email;
// constructor and accessors ommitted
}
首先,请不要使用public static
字段,并在需要时提供访问者。这可以防止其他类直接更改其状态。您还可以将验证逻辑放在那里:
public class IndexCard {
private static Map<String, IndexCard> map = new HashMap<>();
public static void addIndexCard(String dni, IndexCard card) {
if (Utils.validateDni(dni) && !map.containsKey(dni)) {
map.put(dni, card);
} else {
throw new InvalidParameterException();
}
}
private String name;
private String address;
private String phone;
private String email;
// constructor and accessors ommitted
}
您可以使用此类
IndexCard c1 = new EmployeeIndexCard(name, password, adress, phone, email, workArea);
IndexCard.addIndexCard("c1", c1);
IndexCard c2 = new FichaCliente(name, adress, phone, email);
IndexCard.addIndexCard("c2", c2);