记录删除对象的 BlockingQueue 装饰器

发布于 2024-09-03 03:29:36 字数 355 浏览 9 评论 0原文

我有一个 BlockingQueue< /code>在生产者-消费者情况下使用的实现。我想装饰这个队列,以便记录从中获取的每个对象。我知道简单的实现是什么样的:只需实现 BlockingQueue 并在构造函数中接受一个 BlockingQueue ,所有方法都将委托给该构造函数。我还缺少另一种方式吗?也许是图书馆?有回调接口的东西吗?

I have a BlockingQueue implementation that's being used in a producer-consumer situation. I would like to decorate this queue so that every object that's taken from it is logged. I know what the straightforward implementation would look like: simply implement BlockingQueue and accept a BlockingQueue in the constructor to which all of the methods would delegate. Is there another way that I'm missing? A library perhaps? Something with a callback interface?

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

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

发布评论

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

评论(2

写给空气的情书 2024-09-10 03:29:36

我本以为创建一个类来扩展 BlockingQueue 接口的相关实现类,并根据需要覆盖 remove 方法和其他方法会更简单。

编辑

如果OP使用多个BlockingQueue实现,那么创建包装器是一种更好的实现,但它会对所有带来一点性能影响操作和其他小问题。

我的观点是,扩展队列类是包装它的替代方法。是否是更好的选择取决于具体情况。

I'd have thought that it would be simpler to create a class that extends the relevant implementation class for the BlockingQueue interface, and overrides the remove method, and others as required.

EDIT

Creating a wrapper is a better implementation if the OP is using more than one implementation of BlockingQueue, but it introduces a small performance hit on all operations, and other minor issues.

My point is that extending the queue class is an alternative to wrapping it. Whether it is a better alternative depends on the circumstances.

极致的悲 2024-09-10 03:29:36

您可能希望考虑的替代方案是动态代理。这使您可以使用反射式 API 来处理在给定接口上发出的请求 - 将所有调用委托给底层实现将非常简单,同时如果方法名称与 take 方法之一匹配,则添加一些日志记录逻辑。

这种方法的缺点是,它为所有方法调用增加了一点额外的开销(对于一般用途来说几乎可以忽略不计,尽管如果在性能关键部分使用,这应该是一个黄色标志),并且代码最终可能看起来很麻烦。最终,您所做的就是定义与您在帖子中描述的行为完全相同的行为,只不过您不需要显式编写每个委托方法,而是提供一种通配符实现。

An alternative you may wish to consider is dynamic proxies. This lets you use a reflection-style API in order to process requests made on a given interface - it would be very straightforward to delegate all calls to an underlying implementation, while adding some logging logic if the method name matched one of the take methods.

The disadvantage of this approach is that it adds a bit of extra overhead to all method calls (almost certainly negligible for general use though this should be a yellow flag if used in a performance-critical section), and the code can end up looking cumbersome. Ultimately what you're doing is defining exactly the same behaviour that you describe in your post, except you don't need to write each delegating method explicitly but provide a sort of wildcarded implementation.

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