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
|
|
|
|
unless @__instance__
|
2000-12-25 01:29:27 -05:00
|
|
|
Thread.critical = true
|
1999-11-25 04:03:08 -05:00
|
|
|
begin
|
2000-12-25 01:29:27 -05:00
|
|
|
@__instance__ ||= new
|
1999-11-25 04:03:08 -05:00
|
|
|
ensure
|
|
|
|
Thread.critical = false
|
|
|
|
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
|