单例模式、私有方法和单例模块
我正在与 Ruby 中的单例模式作斗争。
我知道单例实现了对象的单个实例,但我不太明白我们是否可以在没有单例模块的情况下复制它。
然后是私有方法的问题;现在我必须做这样的事情:
class MyTestClass
private_class_method :new
class << self
def test
puts hello
end
private
def hello
'hello world'
end
end
end
MyTestClass.test
所以我的问题是:
- 上面是一个好的单例模式吗?
- 这能确保只有一个实例吗?
- 有没有办法使用单例模块来拥有私有方法?
I am fighting with singleton patterns in Ruby.
I know that singleton implements a single instance of an object but I don't quite understand if we can replicate it without the singleton module.
Then there is the issue with private methods; Right now I have to do something like this:
class MyTestClass
private_class_method :new
class << self
def test
puts hello
end
private
def hello
'hello world'
end
end
end
MyTestClass.test
So my questions are:
- Is the above a good Singleton pattern?
- Would this make sure there is only a single instance?
- Is there a way to have private methods using the singleton module?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
?可能不是。仅使用类方法,您无法获得为单个“实例”执行初始化函数的好处,因此它缺少通常在单例中找到的一些部分。 Ruby 足够灵活,因此您可以根据需要将任何缺失的功能附加到“类”对象上,但它开始看起来有点难看。
是的。您正在修改代表该类的对象,并且只有一个对象。
是的。你尝试过吗?正如您所期望的那样。
Probably not. Using only class methods you don't get the benefit of having an
initialize
function executed for your single "instance", so it is missing some pieces you would normally find in a Singleton. Ruby is flexible enough so you can bolt on any missing features to the "class" object as needed, but it starts to look kind of ugly.Yes. You are modifying the object which represents the class, and there is only one.
Yes. Have you tried? Its just as you would expect.