我只是想知道即使这是Object的子类也是如此。
它通过undefining allocate
和new
工作。这里的corresponding C code:
rb_undef_alloc_func(rb_cTrueClass);
rb_undef_method(CLASS_OF(rb_cTrueClass), "new");
您可以通过undef_method
在Ruby中实现类似的结果:
class FooClass
::FOO = new # <- this will be the only Foo instance
class << self
undef_method :allocate
undef_method :new
end
end
FooClass.new #=> NoMethodError: undefined method `new' for FooClass:Class
FooClass.allocate #=> NoMethodError: undefined method `allocate' for FooClass:Class
FOO #=> #<FooClass:0x007fddc284c478>
“相似”,因为TrueClass.allocate
实际上并没有提出一个NoMethodError
,但TypeError
:
TrueClass.allocate #=> TypeError: allocator undefined for TrueClass
不幸的是,rb_undef_alloc_func
在Ruby中不可用。我们可以通过重写allocate
模仿行为:
class FooClass
class << self
def allocate
raise TypeError, "allocator undefined for #{self}"
end
undef_method :new
end
end
FooClass.allocate #=> TypeError: allocator undefined for FooClass
不知道,哪种方式更干净。
上述变化阻止你通过new
创建一个实例,但也有其他的方法:
FOO #=> #<FooClass:0x007fddc284c478>
FOO.dup #=> #<FooClass:0x007fad721122c8>
FOO.clone #=> #<FooClass:0x007f83bc157ba0>
Marshal.load(Marshal.dump(FOO)) #=> #<FooClass:0x007f83bc13e330>
为了考虑所有这些特殊情况,红宝石” STDLIB提供Singleton
模块:
require 'singleton'
class Foo
include Singleton
end
它通过使allocate
和new
私有方法:(间)
Foo.new #=> NoMethodError: private method `new' called for Foo:Class
Foo.allocate #=> NoMethodError: private method `new' called for
,并将其添加instance
返回一个实例:(或的情况下,只有一个)
Foo.instance #=> #<Foo:0x007fdca11117e8>
你想要达到什么目的? –
只是我很想知道它是如何禁止创建新的对象? – Sanjith
您是否阅读过文档? https://ruby-doc.org/core-2.2.0/TrueClass.html –