嗨!
我当前的项目中有一个小设计问题。我有一个类,其中包含有关客户在商店中的时间的信息。
public class Customer {
private String enterTime;
private String leaveTime;
public void enterTimeToInt {
Integer.parseInt(enterTime);
}
public void leaveTimeToInt {
Integer.parseInt(leaveTime);
}
}
现在,在我的程序中,我遇到了一种情况,我必须确定在给定时间商店里是否有任何顾客。现在,我所做的是创建 Customer 类的另一个实例,它代表给定的时间,然后检查它是否与任何“真实”客户匹配。但问题是,我创建了一个在更抽象的意义上代表时间的客户对象,而不是客户。
这种情况我该怎么办?我需要与 Customer 类完全相同的方法和变量,但我认为仅仅创建一个代表随机时间而不是特定客户时间的 Customer 类不是一个好的设计选择。
非常感谢!
最佳答案
Now, what i did was that i made another instance of the Customer class, which represented the given time and then checked if it matches any "real" Customer.
这不是你想要做的。
您想要做的是遍历每个客户一次,并查看该时间是否在 enterTime
和 leaveTime
之间。
编辑回答问题:
我同意这个类的命名很糟糕。该信息与客户有关,因此我将其命名为 CustomerVisit
。
您的 CustomerVisit
类应该看起来更像这样:
import java.util.Calendar;
public class CustomerVisit {
private Calendar enterTime;
private Calendar leaveTime;
public Calendar getEnterTime() {
return enterTime;
}
public void setEnterTime(Calendar enterTime) {
this.enterTime = enterTime;
}
public Calendar getLeaveTime() {
return leaveTime;
}
public void setLeaveTime(Calendar leaveTime) {
this.leaveTime = leaveTime;
}
public boolean isVisit(Calendar givenTime) {
if (givenTime.after(enterTime) && givenTime.before(leaveTime)) {
return true;
} else {
return false;
}
}
public void setVisit(String visitString) {
// File format is hh:mm-hh:mm
String[] times = visitString.split("-");
String[] enterTimeString = times[0].split(":");
String[] leaveTimeString = times[1].split(":");
enterTime = setCalendar(enterTimeString);
leaveTime = setCalendar(leaveTimeString);
}
private Calendar setCalendar(String[] timeString) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,
Integer.valueOf(timeString[0]));
calendar.set(Calendar.MINUTE,
Integer.valueOf(timeString[1]));
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
}
您不需要将时间存储为String
,而是需要将其存储在用于日期/时间计算的对象中,例如Calendar
。
我正在添加一个 SimpleDateFormat
以便您可以显示 enterTime
和
leaveTime
作为字符串。
使用 isVisit
方法,您可以循环访问 CustomerVisit
实例,并查看在 givenTime
访问了哪些客户或多少客户>.
setVisit
方法从文件中获取String
,并将String
转换为Calendar
对象。
关于java - Java 中有 2 个相同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16887496/