1999-08-13 01:45:20 -04:00
|
|
|
# Singleton module that ensures only one object to be allocated.
|
|
|
|
#
|
|
|
|
# Usage:
|
|
|
|
# class SomeSingletonClass
|
|
|
|
# include Singleton
|
|
|
|
# #....
|
|
|
|
# end
|
|
|
|
# a = SomeSingletonClass.instance
|
|
|
|
# b = SomeSingletonClass.instance # a and b are same object
|
|
|
|
# p [a,b]
|
|
|
|
# a = SomeSingletonClass.new # error (`new' is private)
|
|
|
|
|
|
|
|
module Singleton
|
2001-05-06 11:06:00 -04:00
|
|
|
def Singleton.included(klass)
|
1999-08-13 01:45:20 -04:00
|
|
|
klass.private_class_method(:new)
|
|
|
|
klass.instance_eval %{
|
1999-11-17 02:30:37 -05:00
|
|
|
@__instance__ = nil
|
1999-08-13 01:45:20 -04:00
|
|
|
def instance
|
2001-07-31 02:24:45 -04:00
|
|
|
if defined? @__allocating__
|
|
|
|
until @__instance__
|
|
|
|
sleep 0.5
|
|
|
|
end
|
|
|
|
elsif ! @__instance__
|
2000-12-25 01:29:27 -05:00
|
|
|
Thread.critical = true
|
2001-07-31 02:24:45 -04:00
|
|
|
@__allocating__ = true
|
|
|
|
Thread.critical = false
|
1999-11-25 04:03:08 -05:00
|
|
|
begin
|
2001-07-31 02:24:45 -04:00
|
|
|
@__instance__ = new
|
1999-11-25 04:03:08 -05:00
|
|
|
ensure
|
2001-07-31 02:24:45 -04:00
|
|
|
remove_instance_variable(:@__allocating__)
|
1999-11-25 04:03:08 -05:00
|
|
|
end
|
1999-08-13 01:45:20 -04:00
|
|
|
end
|
|
|
|
return @__instance__
|
|
|
|
end
|
|
|
|
}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
if __FILE__ == $0
|
|
|
|
class SomeSingletonClass
|
|
|
|
include Singleton
|
|
|
|
#....
|
|
|
|
end
|
|
|
|
|
|
|
|
a = SomeSingletonClass.instance
|
|
|
|
b = SomeSingletonClass.instance # a and b are same object
|
|
|
|
p [a,b]
|
|
|
|
a = SomeSingletonClass.new # error (`new' is private)
|
|
|
|
end
|