# The Singleton module implements the Singleton pattern.
# * this ensures that only one instance of Klass lets call it
# ``the instance'' can be created.
# a,b = Klass.instance, Klass.instance
# a.new # NoMethodError - new is private ...
# * ``The instance'' is created at instantiation time, in other
# words the first call of Klass.instance(), thus
# ObjectSpace.each_object(OtherKlass){} # => 0.
# * This behavior is preserved under inheritance and cloning.
# This is achieved by marking
# * Klass.new and Klass.allocate - as private
# Providing (or modifying) the class methods
# * Klass.inherited(sub_klass) and Klass.clone() -
# to ensure that the Singleton pattern is properly
# * Klass.instance() - returning ``the instance''. After a
# successful self modifying (normally the first) call the
# method body is a simple:
# * Klass._load(str) - calling Klass.instance()
# * Klass._instantiate?() - returning ``the instance'' or
# nil. This hook method puts a second (or nth) thread calling
# Klass.instance() on a waiting loop. The return value
# signifies the successful completion or premature termination
# of the first, or more generally, current "instantiation thread".
# The instance method of Singleton are
# * clone and dup - raising TypeErrors to prevent cloning or duping
# * _dump(depth) - returning the empty string. Marshalling strips
# by default all state information, e.g. instance variables and
# taint state, from ``the instance''. Providing custom _load(str)
# and _dump(depth) hooks allows the (partially) resurrections of
# a previous state of ``the instance''.
# disable build-in copying methods
raise TypeError, "can't clone instance of singleton #{self.class}"
raise TypeError, "can't dup instance of singleton #{self.class}"
# default marshalling strategy
# Method body of first instance call.
FirstInstanceCall = proc do
# @__instance__ takes on one of the following values
# * nil - before and after a failed creation
# * false - during creation
# * sub_class instance - after a successful creation
# the form makes up for the lack of returns in progs
def instance; @__instance__ end
@__instance__ = nil # failed instance creation
def instance; @__instance__ end
module SingletonClassMethods
# properly clone the Singleton pattern - did you know
# that duping doesn't copy class methods?
Singleton.__init__(super)
# ensure that the Singleton pattern is properly inherited
Singleton.__init__(sub_klass)
while false.equal?(@__instance__)
klass.instance_eval { @__instance__ = nil }
define_method(:instance,FirstInstanceCall)
# extending an object with Singleton is a bad idea
undef_method :extend_object
# help out people counting on transitive mixins
unless mod.instance_of?(Class)
raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
klass.private_class_method :new, :allocate
klass.extend SingletonClassMethods
Singleton.__init__(klass)
def num_of_instances(klass)
"#{ObjectSpace.each_object(klass){}} #{klass} instance(s)"
# The basic and most important example.
puts "There are #{num_of_instances(SomeSingletonClass)}"
a = SomeSingletonClass.instance
b = SomeSingletonClass.instance # a and b are same object
puts "basic test is #{a == b}"
rescue NoMethodError => mes
puts "\nThreaded example with exception and customized #_instantiate?() hook"; p
Thread.abort_on_exception = false
class Ups < SomeSingletonClass
puts "initialize called by thread ##{Thread.current[:i]}"
@enter.push Thread.current[:i]
while false.equal?(@__instance__)
@leave.push Thread.current[:i]
raise "boom - thread ##{Thread.current[:i]} failed to create instance"
rescue RuntimeError => mes
puts "Before there were #{num_of_instances(self)}"
puts "Now there is #{num_of_instances(self)}"
puts "#{@enter.join '; '} was the order of threads entering the waiting loop"
puts "#{@leave.join '; '} was the order of threads leaving the waiting loop"
# results in message like
# Before there were 0 Ups instance(s)
# boom - thread #6 failed to create instance
# initialize called by thread #3
# Now there is 1 Ups instance(s)
# 3; 2; 1; 8; 4; 7; 5 was the order of threads entering the waiting loop
# 3; 2; 1; 7; 4; 8; 5 was the order of threads leaving the waiting loop
puts "\nLets see if class level cloning really works"
raise "boom - thread ##{Thread.current[:i]} failed to create instance"
puts "\n\n","Customized marshalling"
attr_accessor :persist, :die
# this strips the @die information from the instance
Marshal.dump(@persist,depth)
instance.persist = Marshal.load(str)
stored_state = Marshal.dump(a)
b = Marshal.load(stored_state)
p a.persist # => ["persist"]
puts "\n\nSingleton with overridden default #inherited() hook"
def Up.inherited(sub_klass)
puts "#{sub_klass} subclasses #{self}"
puts "and basic \"Down test\" is #{Down.instance == Down.instance}\n
puts mes #=> Inclusion of the OO-Singleton module in module AModule
'aString'.extend Singleton
rescue NoMethodError => mes
puts mes #=> undefined method `extend_object' for Singleton:Module