0

I need class that has singleton behaviour.

What's the difference between using the Singleton module...

require 'singleton'

class X
    include Singleton

    def set_x(x)
        @x = x
    end

    def test
        puts @x
    end
end

X::instance.set_x('hello')
X::instance.test

...and using class methods and class instance variables?

class X
    def self.set_x(x)
        @x = x
    end

    def self.test
        puts @x
    end
end

X::set_x('hello')
X::test
AJM
  • 655
  • 1
  • 9
  • 19
  • 1
    IMHO the main difference is communicating the intent of what you are trying to do, which is more obvious if you `include Singleton`. – Michael Kohl Sep 12 '11 at 06:42

1 Answers1

1

Nothing, as you wrote your code--but a singleton is a class that only allows a single instance. Nothing in the second code snippet disallows instantiation of multiple instances.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • So in the first code snippet it's still possible to write 't = X.new'? – AJM Sep 12 '11 at 00:38
  • 1
    Seems like it'd be quicker to try it, no? But no, it isn't possible (at least without an error). The singleton part of it removes the `new` method from public view--that's why there's an `instance` method. An alternative would have been to have `new` return the single instance, but it's arguably less communicative. – Dave Newton Sep 12 '11 at 00:46
  • Yeah, it would have been quicker to try it. I just wanted to make sure that that was the major difference. – AJM Sep 12 '11 at 03:59