由於我們在談論理論,所以我指出了一些事實,並從設計角度講。
靜態方法沒有關聯到某個類的特定實例,因此重寫不是一個選項,因爲它取決於具有一個實例。我在談論Java,因爲我記得一些允許使用類方法重寫的其他語言。
的解決方法,這是在返回它感興趣的事件,每個子類定義一個靜態方法,這樣你就可以知道實例在此之前的數據。
另一種選擇是把一個特定的類負責這些對象實例化,使該類保持表的事件與相關類(表,你可以初始化和配置)的列表關聯。這種方法似乎更易於維護,因爲如果要從事件中取消類別,則不必更改代碼。
最後,你只需實例化綜合類再關聯到某個事件的所有類:
public class EventClassCreator {
private Map<String, List<String>> subscriptions;
public EventClassCreator() {
subscriptions = new HashMap<String,Set<String>>();
}
public void addSubscription(String event, String class) {
if(subscriptions.containsKey(event))
subscriptions.get(event).add(class);
else {
Set<String> subscriptionsForEvent = new HashSet<String>();
subscriptionsForEvent.add(class);
subscriptions.put(event, subscriptionsForEvent);
}
}
//You just need to make an event that loops over the list of classes,
//checks a subscription and instantiates a class if it is in the
//proper list.
}
這類聲音就像一個番石榴['EventBus'](https://code.google.com/p/guava-libraries/wiki/EventBusExplained),除了實例部分。 –