The following is the singleton pattern in Ruby:
and you can define two instances of this class by the instance method like this:
then you can use this code to test whether the two instances are the same reference or not:
If you run these codes,you can get 'true' in your console.
But there is a problem,this class can't work in mutl-thread environment,is it right?
ruby 代码
- class Singleton
- private_class_method :new
- @@instance = nil
- def Singleton.instance
- if(@instance == nil)
- @instance = new
- end
- return @instance
- end
- end
ruby 代码
- s = Singleton.instance
- s2 = Singleton.instance
then you can use this code to test whether the two instances are the same reference or not:
ruby 代码
- puts s.equal?(s2)
But there is a problem,this class can't work in mutl-thread environment,is it right?