0

我的家庭作业是弄清楚:

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

代码

/// 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; 
    }
}

我浏览了代码并发现此代码尝试生成天气报告并根据eventReceivedEvent可以注册/取消注册)对天气状况进行分类。

但是,我看不到代码有任何问题。我的老师坚持说有问题。谁能帮我?

4

1 回答 1

2

首先,Event不应该是一个enum. 因为它的成员实际上是单身人士;通过更改one 的 eg 严重性TORNADO,您将更改所有这些的严重性。你应该有一个 for 的枚举EventType,一个 forSeverity和一个Event使用它们的类。

然后,您在事件发布者中的地图将会改变......

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

于 2012-04-20T00:17:47.037 回答