首先,F# 中的函数式风格和面向对象的风格并没有真正的冲突。
在基于代理的系统中,在代理的实现中使用函数式风格是很有意义的,但使用类来组织代理。我认为这可能是 F# 中的最佳实践(另请参阅这篇关于 MSDN 上封装 F# 代理的文章)。
在您的示例中,您说代理保留了它向其发送消息的其他代理的列表。有一些替代方案值得考虑(如果你想避免接口):
Expose an F# event (Event<'T>
). This way, the agent simply exposes a notification and does not have to explicitly manage a list of other agents (and this design also allows other types of subscribers).
Keep a list of functions. If you just need to send messages to other agents, then you essentially need just an interface with a single method. In that case, you could keep a list of functions such as
Message -> unit
.
I generally prefer exposing events - this way, the system is less tightly coupled and you can more easily compose agents in various ways (they do not have to implement a specific interface to be composed). This article discusses agent-based architectures from a higher-level perspective, and may be useful too.