在Ruby中,如何实现全局行为?
我想实现工作区的概念。这是一个全局概念 - 所有其他代码都将与此工作区的一个实例交互。工作区将负责维护当前的系统状态(即与系统模型交互、保留系统状态等)
那么我的工作区的最佳设计策略是什么,记住这必须是可测试的(现在使用 RSpec,但是很乐意寻找替代方案)。
阅读了一些开源项目后,我发现了 3 种策略。我无法将其中任何一个视为“最佳实践”。
它们是:
- 包含
singleton
类。但是这有多可测试呢? Workspace 的全局状态在测试之间会发生变化吗? - 将所有行为实现为类方法。您如何测试这一点?
- 将所有行为实现为模块方法。对此完全不确定!
哪个最好?或者还有别的办法吗?
谢谢, Gordon
编辑
当我开始在所有代码中包含“单例”模块时,我意识到我的代码与各地的这些全局实例的引用是多么紧密地耦合。
因此,我开始完全删除它们并传递对全局实例的引用。但现在我正沿着 IOC 的路线前进——通过我的构造函数向下传递依赖项。
这在 Ruby 中是个好主意吗?或者我错过了什么?
顺便说一句,您可能已经知道我是 Ruby 新手!
I want to implement the concept of a Workspace. This is a global concept - all other code will interact with one instance of this Workspace. The Workspace will be responsible for maintaining the current system state (i.e. interacting with the system model, persisting the system state etc)
So what's the best design strategy for my Workspace, bearing in mind this will have to be testable (using RSpec now, but happy to look at alternatives).
Having read thru some open source projects out there and I've seen 3 strategies. None of which I can identify as "the best practice".
They are:
- Include the
singleton
class. But how testable is this? Will the global state of Workspace change between tests? - Implemented all behaviour as class methods. Again how do you test this?
- Implemented all behaviour as module methods. Not sure about this one at all!
Which is best? Or is there another way?
Thanks,
Gordon
Edit
As I started including the 'singleton' module in all my code and I realised just how tightly coupled I had made my code, with references to these global instances all over the place.
So I've started to remove them entirely and pass references to the global instances instead. But now I'm heading down the route of IOC - passing dependencies down through my constructers.
Is this a good idea in Ruby? Or am I missing something?
BTW you may have gathered I'm new to Ruby!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许标准库中的 Singleton 模块 会有用?如果您将此模块包含在您的类中,则只能创建它的一个实例。然后,您可以使用实例变量来管理工作区的状态等。
如果这就是您所说的“包含单例类”的意思,那么我很抱歉,但是术语“单例”在 Ruby 领域中经常被使用,通常在此上下文中。
Maybe the Singleton module from the standard library would be useful? If you include this module in your class, only one instance of it can be created. You then can use instance variables for managing the state of your workspace etc.
If this was what you meant by "Include the singleton class", then I'm sorry, but the term "singleton" gets thrown around quite a bit in Ruby land, usually in this context.
从性能角度来看,单例方法是最佳选择。为了在测试期间不改变它,您可以使用模型。
The singleton approach is best choice, performance wise. For it not to change during tests you can use a mock up.