문제

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
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top