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
|
|
|
|
def Singleton.append_features(klass)
|
|
|
|
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
|
2000-02-29 03:05:32 -05:00
|
|
|
Thread.critical = true
|
1999-08-13 01:45:20 -04:00
|
|
|
unless @__instance__
|
1999-11-25 04:03:08 -05:00
|
|
|
begin
|
|
|
|
@__instance__ = new
|
|
|
|
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
|