了解企业应用程序上下文中的 FP(在 Scala 中)
我看到的大多数示例(如果不是全部)都是执行某种计算并完成的函数。在这方面,FP 很耀眼。但是,我很难了解如何将其应用到企业应用程序环境中,因为企业应用程序环境中没有太多算法,也没有大量数据传输和服务。
所以我想问一下如何以FP风格实现以下问题。
我想实现事件总线服务。该服务具有用于注册侦听器的 register
方法和用于发布事件的 publish
方法。
在 OO 设置中,这是通过使用这两种方法创建 EventBus 接口来完成的。然后,实现可以使用列表来保存由 register
更新并在 publish
中使用的侦听器。当然,这意味着register
有副作用。 Spring 可用于创建该类并将其实例传递给事件的发布者或订阅者。
考虑到事件总线服务的客户端是独立的(例如,并非所有客户端都是在“测试”方法中创建的),如何在 FP 中对此进行建模?据我所知,这否定了注册返回 EventBus 的新实例,因为其他客户端已经持有对旧实例的引用(例如,发布到它只会发布到它知道的侦听器)
我更喜欢以下解决方案在 Scala 中。
Most examples (if not all) that I see are the sort of a function that does some sort of computation and finishes. In that aspect, FP shines. However, I have trouble seeing how to apply it in the context of an enterprise application environment where there's not much of algorithms going on and a lot of data transfer and services.
So I'd like to ask how to implement the following problem in FP style.
I want to implement an events bus service. The service has a register
method for registering listeners and publish
for publishing events.
In an OO setting this is done by creating an EventBus interface with both methods. Then an implementation can use a list to hold listeners that is updated by register
and used in publish
. Of course this means register
has a side effect. Spring can be used to create the class and pass its instance to publishers or subscribers of events.
How to model this in FP, given that clients of the event bus service are independent (e.g., not all are created in a "test" method)? As far as I can see this negates making register return a new instance of EventBus, since other clients already hold a reference to the old instance (and e.g., publishing to it will only publish to the listeners it knows of)
I prefer a solution to be in Scala.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你应该仔细研究一下函数式反应式编程技术。既然你想要 Scala 中的东西,我建议阅读 弃用观察者模式论文英戈·迈尔、蒂亚克·朗普夫和马丁·奥德斯基。
I think you should have a closer look at functional reactive programming techniques. Since you want something in Scala, I suggest reading Deprecating The observer pattern paper by Ingo Maier, Tiark Rompf and Martin Odersky.
解决方案的概要是发布应该返回
IO[Unit]
。听众应该是迭代者。注册还会返回IO[Unit]
。The sketch of the solution is that publish should return
IO[Unit]
. Listeners should be iteratees. Registration also returnsIO[Unit]
.