CDI - 事件观察者
我有事件观察者,它们都观察相同的事件,所以我有一个抽象超类,它观察该事件,然后子类覆盖/实现特定功能。
这样做的问题是,除非我将事件观察者方法放在子类中,否则它不会观察事件(这违背了我的设计目的)。
我当然可以这样做,但我想编写尽可能少的代码。
它应该这样工作吗(我做错了什么吗)?
如果它不应该以这种方式工作,那么我可以为一件事编写一个生产者,然后编写一个拦截器。我认为我的第一种方法更简单,并且更有可能被其他开发人员正确使用。
示例代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要么将超类中的相关方法声明为抽象方法,要么让它调用每个子类实现的抽象“详细”方法。
Either declare the relevant method in the superclass to be abstract or have it call an abstract "detail" method that each subclass implements.
正如我上面提到的,我写了一个装饰器。这本质上是做同样的事情,只是写法略有不同。
沃尔特
I wrote a decorator as I mentioned above. This essentially does the same thing, just written slightly differently.
Walter