我的家庭工作任务是弄明白:
代码
/// Enum
public enum Event {
TORNADO, THUNDERSTORM, TSUNAMI, RAIN, SNOW, WIND, COLD, HEAT;
public final static String CRITICAL = "Critical";
public final static String SEVERE = "Severe";
public final static String MEDIUM = "Medium";
public final static String LIGHT = "Light";
private String severity;
private String location;
public void setSeverity(String severity) {
this.severity = severity;
}
public void setLocation(String location) {
this.location = location;
}
public String toString() {
return super.toString() + ":" + severity + " at " + location;
}
}
///Interface
public interface IEventListener {
void eventReceived(Event event);
}
///Class
public class EventPublisher implements IEventListener {
Map<Event, Collection<IEventListener>> listeners = new HashMap<Event, Collection<IEventListener>>();
@Override
public synchronized void eventReceived(Event event) {
for (IEventListener listener : listeners.get(event)){
listener.eventReceived(event);
}
}
public synchronized void register(IEventListener listener, Event event){
Collection<IEventListener> list = listeners.get(event);
if (list == null) {
list = new LinkedList<IEventListener>();
listeners.put(event, list);
}
list.add(listener);
}
public synchronized void deregister(IEventListener listener, Event event) {
listeners.get(event).remove(listener);
}
public String toString() {
String ret = "";
Iterator<Event> i = listeners.keySet().iterator();
while (i.hasNext()) {
Iterator<IEventListener> j = listeners.get(i.next()).iterator();
while (j.hasNext()) {
ret = ret + i.next() + "::" + j.next() + "\n";
}
}
return ret;
}
}
我仔细检查了代码并发现此代码会尝试生成天气预报并根据eventReceived
对天气状况进行分类(Event
可以注册/注销)。
但是我看不到代码的任何问题。我的老师坚持认为有问题。任何人都可以帮助我吗?
答案 0 :(得分:2)
首先,Event
不应该是enum
。由于其成员是有效的单身人士;通过改变例如一个 TORNADO
的严重性,您将更改所有的严重性。您应该有EventType
的枚举,Severity
的枚举和使用它们的Event
类。
然后,您在事件发布者中的地图将更改...
此外,deregister
方法可能会抛出空引用异常...