Python vs Ruby Singleton

I had dug a bit into Singleton Pattern in JavaScript lately and also was playing with some Python and Ruby Singleton Design pattern and asstonisginly they are very simple and one can enjoy reading the code, as so little code helps one to implement this pattern.

First up is python :

# python -m doctest singleton.py
class Singleton(object):
 """
 >>> single = Singleton()
  >>> single #doctest: +ELLIPSIS
    <hidden.Singleton object at 0x...>
   >>> one = Singleton()
 >>> one == single
 True
   """
 def <strong>new</strong>(clz, *args, **kargs):
      if not hasattr(clz, '_inst'):
            clz._inst = super(Singleton, clz).__new__(clz, *args, **kargs)
     return cls._inst

Ruby turn, yes ruby has stdlib 'singelton', so all one needs to do is :

>> class Spinster
>>   include Singleton
>> end
=> Spinster
>> lady = Spinster.new
NoMethodError: private method `new' called for Spinster:Class
    from (irb):14
>> lady = Spinster.instance
=> #<Spinster:0x1004a4420>

Hope you had fun, happy hacking!

Further reading :

The Borg design pattern

Ruby doc

Share this