gpt4 book ai didi

java - 简单的天气预报 Java 代码

转载 作者:行者123 更新时间:2023-12-02 07:50:55 26 4
gpt4 key购买 nike

我的家庭作业是弄清楚:

  • 这段代码的作用
  • 存在哪些潜在问题

代码

/// 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 可以注册/取消注册) .

但是我看不出代码有任何问题。我的老师坚持认为存在问题。谁能帮我吗?

最佳答案

首先,Event 不应该是enum。因为它的成员实际上都是单例;通过改变例如一个TORNADO的严重性,您可以更改全部的严重性。您应该有一个 EventType 枚举、一个 Severity 枚举以及一个使用它们的 Event 类。

然后,您在事件发布者内的 map 将会改变...

此外,deregister 方法可能会引发空引用异常...

关于java - 简单的天气预报 Java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10238574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com