Event Registry design pattern?
I have a list of events that i need to fire when a user takes an action and an event manager that fires these events.
Originally i used to fire the events explicitly in this way
EventManager.publish(new SendNotificationEvent())
Then i wanted to change that to something like
EventManager.publishSendNotificationEvent()
To do that, i need to dynamically load the class "SendNotificationEvent", instantiate it and fire the event. Dealing with ClassLoder dynamically uses reflection, 开发者_运维百科slow and a pain to deal with. So I thought of registering the event when the root class Event is loaded
Event {
Map registry = [:]
static {
registry["SendNotificationEvent"] = SendNotificationEvent.class
}
Class get(String key) {
return registry[key]
}
}
and change the event manage to resolve the event class through Event
EventManager {
Class $static_methodMissing (String name, args) {
def event Event.get(name-"fire").metaClass.invokeConstructor(args)
fire(event)
}
}
Is this a good approach, is there a design pattern that i can use to do this better or should I just live with ClassLoader pain and make it work ...
- ken
I like your first way better (and I have to agree with FabrizioM's comment - why?)
I like EventManager.publish(new SendNotificationEvent())
because the EventManager
doesn't know anything about the events; this will make your system much easier to maintain (etc).
Coding is like a form of exercise: if it starts to hurt you should stop.
精彩评论