这是一道 OOD 题。设计日历。 要求是:
- 添加事件
- 删除事件
- 获取特定日期的所有事件
验证数据结构并设计测试用例
我知道我需要提供 addEvent()、deleteEvent()、getEventByDay() 等 API
我停留在第一个 API,添加一个事件。 我提出了两种解决方案,我只是不知道哪种模式更好,为什么。
版本 1:
public class Calender {
// helper class
public static class Event {
String name;
Event(String s) {
name = s;
}
}
Calender() {
}
// API
public void addEvent(Event e) {
// todo
}
// driver function
public static void main(String[] args) {
Calender calender = new Calender();
Event event = new Event("event");
calender.addEvent(event);
}
}
版本 2:
public class Calender {
int systemId;
// helper class
public static class Event {
String name;
Event(String s) {
name = s;
}
}
Calender() {
}
// API
public int addEvent(String s) {
Event event = new Event(s);
systemId++;
return systemId - 1; // after add an event, return the unique id for it
}
// driver function
public static void main(String[] args) {
Calender calender = new Calender();
int id = calender.addEvent("a");
}
}
以上类(class)未完成。 主要区别在于我们是否需要让用户创建事件然后添加此实例,还是仅使用现有 API 创建事件并为该事件获取唯一 ID?
最佳答案
我会保留这两种方法。允许用户插入新的 Event
对象或只传递字符串并添加它。
public class Calendar {
public static class Event {
String name;
Event(String s) {
name = s;
}
}
Calendar() {
}
public void addEvent(Event e) {
// todo
}
public int addEvent(String s) {
Event event = new Event(s);
systemId++;
return systemId - 1; // after add an event, return the unique id for it
}
}
也就是说,我会执行以下操作:
- 从
Calendar
类中删除main
,它应该在一个单独的Application
类中,例如,它将实例化您的日历。 - 不是在添加事件时返回事件 ID,而是在
Event
类中添加一个字段id
,用新 ID 填充它,然后返回整个事件
对象。 - 也许将
Event
类放在一个单独的文件中,而不是将其放在Calendar
中。它是否有意义是有争议的,所以留给你欣赏。
除此之外,您应该将事件列表存储在您的日历中,以便能够返回整个事件列表或删除一个事件,如您的练习主题所述。
关于java - 如何设计日历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53389946/