如何在 Ruby 中将类构造函数设为私有?
class A
private
def initialize
puts "wtf?"
end
end
A.new #still works and calls initialize
并且
class A
private
def self.new
super.new
end
end
并不完全有效
那么正确的方法是什么?我想将 new
设为私有并通过工厂方法调用它。
class A
private
def initialize
puts "wtf?"
end
end
A.new #still works and calls initialize
and
class A
private
def self.new
super.new
end
end
doesn't work altogether
So what's the correct way? I want to make new
private and call it via a factory method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
有关 APIDock 的更多信息
Try this:
More on APIDock
为了说明用法,下面是一个常见的工厂方法示例:
然后按预期使用它
,直接使用
new
会出现运行时错误:To shed some light on the usage, here is a common example of the factory method:
Then use it as
As expected, the runtime error occurs in the case of direct
new
usage:您尝试的第二块代码几乎是正确的。问题是
private
是在实例方法而不是类方法的上下文中操作的。要让
private
或private :new
工作,您只需强制它位于类方法的上下文中,如下所示:或者,如果您确实想重新定义 < code>new 并调用
super
类级工厂方法可以访问私有的
new
就好了,但是尝试直接使用new
实例化> 将失败,因为new
是私有的。The second chunk of code you tried is almost right. The problem is
private
is operating in the context of instance methods instead of class methods.To get
private
orprivate :new
to work, you just need to force it to be in the context of class methods like this:Or, if you truly want to redefine
new
and callsuper
Class-level factory methods can access the private
new
just fine, but trying to instantiate directly usingnew
will fail becausenew
is private.