module Singleton
TheSingleton module implements theSingleton pattern.
Usage¶↑
To useSingleton, include the module in your class.
classKlassincludeSingleton# ...end
This ensures that only one instance of Klass can be created.
a,b =Klass.instance,Klass.instancea==b# => trueKlass.new# => NoMethodError - new is private ...
The instance is created at upon the first call of Klass.instance().
classOtherKlassincludeSingleton# ...endObjectSpace.each_object(OtherKlass){}# => 0OtherKlass.instanceObjectSpace.each_object(OtherKlass){}# => 1
This behavior is preserved under inheritance and cloning.
Implementation¶↑
This above is achieved by:
Making Klass.new and Klass.allocate private.
Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that the
Singletonproperties are kept when inherited and cloned.Providing the Klass.instance() method that returns the same object each time it is called.
Overriding Klass._load(str) to call Klass.instance().
Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent cloning or duping.
Singleton andMarshal¶↑
By default Singleton’s_dump(depth) returns the empty string. Marshalling by default will strip state information, e.g. instance variables from the instance. Classes usingSingleton can provide custom _load(str) and _dump(depth) methods to retain some of the previous state of the instance.
require'singleton'classExampleincludeSingletonattr_accessor:keep,:stripdef_dump(depth)# this strips the @strip information from the instanceMarshal.dump(@keep,depth)enddefself._load(str)instance.keep =Marshal.load(str)instanceendenda =Example.instancea.keep ="keep this"a.strip ="get rid of this"stored_state =Marshal.dump(a)a.keep =nila.strip =nilb =Marshal.load(stored_state)pa==b# => truepa.keep# => "keep this"pa.strip# => nil
Constants
- VERSION
Public Class Methods
Source
# File lib/singleton.rb, line 190By default calls instance(). Override to retain singleton state.
Source
# File lib/singleton.rb, line 146defself.module_with_class_methodsSingletonClassMethodsend