Java 委托事件模型模式

发布于 2024-11-04 13:49:29 字数 379 浏览 0 评论 0原文

当应用此模式委托事件模型时,将所有代码放在 fire... 方法中并从公共方法传递参数是否正确?

像这样

public void addBananas(Banana banana) {
    fireBananaAdded(banana);  
}

private void fireBananaAdded(Banana banana) {
    //Create event etc and add banana to list here
}

或者我应该在 addBananas 方法中使用此示例中的添加到列表部分吗?因为如果我这样做,我将没有机会将香蕉对象“附加”到将传递给侦听器的事件对象,对吗?

When applying this pattern Delegation Event Model, is it correct to put ALL the code in the fire... methods and pass the parameters from the public method?

Like this

public void addBananas(Banana banana) {
    fireBananaAdded(banana);  
}

private void fireBananaAdded(Banana banana) {
    //Create event etc and add banana to list here
}

Or should I have the add to list part in this example in the addBananas method instead? Because if I do it this way I will not have the opportunity to "attach" the banana object to the event-object which will be passed to the listeners, right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画▽骨i 2024-11-11 13:49:29

我会在 addBanana() 中放入尽可能多与实际添加香蕉相关的逻辑。

当我完成 addBanana() 后,我会调用 fireBananaAdded() ,它将生成适当的 BananaAddedEvent 并将其发送到 BananaAddedListeners(或者只是 BananaListeners,无论您有什么。)

将 ADD 逻辑放入 FIRE 方法中就是简单的,嗯,BANANAS!

public void addBananas(Banana banana) {
    if(BananaHolder.hasRoom()) {
        BananaHolder.add(banana);
        fireBananaAdded(banana);  
    }
}

private void fireBananaAdded(Banana banana) {
    BananaAddedEvent event = new BananaAddedEvent(banana);
    for(BananaListener listener : listenersByType(Banana.class)) {
        listener.bananaAdded(event);
    }
}

I would put as much logic in addBanana() that is related to actually adding the Banana as I can.

When I'm done with addBanana(), I would call fireBananaAdded() which would generate the appropriate BananaAddedEvent and send it to the BananaAddedListeners (or just BananaListeners, which ever you have.)

To put the ADD logic in the FIRE method is simply, well, BANANAS!

public void addBananas(Banana banana) {
    if(BananaHolder.hasRoom()) {
        BananaHolder.add(banana);
        fireBananaAdded(banana);  
    }
}

private void fireBananaAdded(Banana banana) {
    BananaAddedEvent event = new BananaAddedEvent(banana);
    for(BananaListener listener : listenersByType(Banana.class)) {
        listener.bananaAdded(event);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文