开发者

Event Registry design pattern?

开发者 https://www.devze.com 2023-01-22 08:52 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消