我在我的应用程序中实现工厂模式的方式,并且工作正常,除了以下代码块(我有另一个,对于另一个类更大)。有没有办法重构这个"丛林" -structure?提前谢谢!
private Goal createLocalTaskInstance(HashMap<String, Object> goalDetails){
Goal goal = null;
if (goalDetails.get("description") == null &&
goalDetails.get("endDate") == null){
goal = new Task(String.valueOf(goalDetails.get("title")));
} else if (goalDetails.get("description") != null &&
goalDetails.get("endDate") == null) {
goal = new Task(String.valueOf(goalDetails.get("title")),
String.valueOf(goalDetails.get("description")));
} else if (goalDetails.get("description") == null &&
goalDetails.get("endDate") != null) {
goal = new Task(String.valueOf(goalDetails.get("title")),
(Date) goalDetails.get("endDate"));
} else if (goalDetails.get("description") != null &&
goalDetails.get("endDate") != null){
goal = new Task(String.valueOf(goalDetails.get("title")),
String.valueOf(goalDetails.get("description")),
(Date) goalDetails.get("endDate"));
}
return goal;
}
答案 0 :(得分:3)
我建议您只需调用默认构造函数(包含所有三个参数),无论它们中的某些是否为null,然后只需在构造函数中执行null检查。它看起来像这样:
goal = new Task(String.valueOf(goalDetails.get("title"),
goalDetails.get("description"),
goalDetails.get("endDate"));
任务类:
public class Task {
private String title;
private String description;
private Date endDate;
public Task(String title, String description, Date endDate) {
this.title = title;
if(description != null) {
this.description = description;
}
if(endDate != null) {
this.endDate = endDate;
}
}
}