gpt4 book ai didi

design-patterns - 事件注册表设计模式?

转载 作者:行者123 更新时间:2023-12-02 14:55:47 35 4
gpt4 key购买 nike

我有一个事件列表,当用户执行操作时需要触发这些事件,还有一个事件管理器将触发这些事件。

最初我曾经以这种方式明确触发事件

EventManager.publish(new SendNotificationEvent())

然后我想将其更改为
EventManager.publishSendNotificationEvent()

为此,我需要动态加载类“SendNotificationEvent”,实例化它并触发事件。动态处理ClassLoder会使用反射,缓慢和痛苦的处理方式。所以我想到了在加载根类Event时注册事件
Event {
Map registry = [:]
static {
registry["SendNotificationEvent"] = SendNotificationEvent.class
}

Class get(String key) {
return registry[key]
}
}

并更改事件,以通过事件解决事件类
EventManager {
Class $static_methodMissing (String name, args) {
def event Event.get(name-"fire").metaClass.invokeConstructor(args)
fire(event)
}
}

这是一个好方法吗?是否可以使用一种设计模式来做得更好?还是我应该忍受ClassLoader的痛苦并使其工作...
  • ken
  • 最佳答案

    我更喜欢您的第一种方式(而且我必须同意FabrizioM的评论-为什么?)

    我喜欢EventManager.publish(new SendNotificationEvent()),因为EventManager对事件一无所知。这将使您的系统更易于维护(等)。

    编码就像一种锻炼:如果开始受伤,就应该停止。

    关于design-patterns - 事件注册表设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4054057/

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