CDI - 事件观察者

发布于 2024-09-16 14:16:24 字数 841 浏览 5 评论 0原文

我有事件观察者,它们都观察相同的事件,所以我有一个抽象超类,它观察该事件,然后子类覆盖/实现特定功能。

这样做的问题是,除非我将事件观察者方法放在子类中,否则它不会观察事件(这违背了我的设计目的)。

我当然可以这样做,但我想编写尽可能少的代码。

它应该这样工作吗(我做错了什么吗)?

如果它不应该以这种方式工作,那么我可以为一件事编写一个生产者,然后编写一个拦截器。我认为我的第一种方法更简单,并且更有可能被其他开发人员正确使用。

示例代码:

SuperClass:

public abstract class AbstractFileWriter
{
  public void onReady(@Observes ReadyEvent readyEvent)
  {
    try
    {
      handleReady(readyEvent, ...);
    }
  }

  protected abstract handleReady(ReadyEvent readyEvent, otherParameters go here);
}

SubClass

public class XmlWriter extends AbstractFileWriter
{
   protected handleReady( ... )
   { ... }
}

如果我这样写,则永远不会调用handleReady(并且 onReady 也不会调用);但是,如果我在子类中使用观察者方法编写它,它会按预期工作。我想以这种方式编写它,因为我需要编写的代码要少得多,抽象也少一点,这应该使它更容易理解。

沃尔特

I have event observers which all observe the same event, so I have an abstract superclass which observes that event and then the subclass overrides / implements the specific functionality.

The problem with this is that it doesn't observe the event unless I put the event observer method in the subclass (which defeats the purpose of my design).

I can most certainly do it this way, but I want to write as little code as possible.

Should it work this way (am I doing something else wrong)?

If it isn't supposed to work this way, then I can write a producer for one thing and then an interceptor. I thought that my first approach was simpler and more likely to be used properly by other developers.

example code:

SuperClass:

public abstract class AbstractFileWriter
{
  public void onReady(@Observes ReadyEvent readyEvent)
  {
    try
    {
      handleReady(readyEvent, ...);
    }
  }

  protected abstract handleReady(ReadyEvent readyEvent, otherParameters go here);
}

SubClass

public class XmlWriter extends AbstractFileWriter
{
   protected handleReady( ... )
   { ... }
}

If I write it this way, handleReady is never invoked (and neither is onReady for that matter); however, if I write it with the observer method within the subclass, it works as expected. I want to write it this way as there is much less code I'd have to write and a little bit less abstraction which should make it easier to understand.

Walter

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

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

发布评论

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

评论(2

尴尬癌患者 2024-09-23 14:16:24

要么将超类中的相关方法声明为抽象方法,要么让它调用每个子类实现的抽象“详细”方法。

Either declare the relevant method in the superclass to be abstract or have it call an abstract "detail" method that each subclass implements.

浅笑轻吟梦一曲 2024-09-23 14:16:24

正如我上面提到的,我写了一个装饰器。这本质上是做同样的事情,只是写法略有不同。

沃尔特

I wrote a decorator as I mentioned above. This essentially does the same thing, just written slightly differently.

Walter

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文