| Module | Singleton |
| In: |
lib/singleton.rb
|
The Singleton module implements the Singleton pattern.
Usage:
class Klass
include Singleton
# ...
end
a,b = Klass.instance, Klass.instance a == b # => true a.new # NoMethodError - new is private …
class OtherKlass
include Singleton
# ...
end
ObjectSpace.each_object(OtherKlass){} # => 0.
This is achieved by marking
Providing (or modifying) the class methods
def Klass.instance()
return @__instance__
end
The instance method of Singleton are
disable build-in copying methods
# File lib/singleton.rb, line 67
67: def clone
68: raise TypeError, "can't clone instance of singleton #{self.class}"
69: end
# File lib/singleton.rb, line 70
70: def dup
71: raise TypeError, "can't dup instance of singleton #{self.class}"
72: end