开发者

Singleton module or class methods + class instance variables for singleton-like behaviour in Ruby?

开发者 https://www.devze.com 2023-04-04 08:12 出处:网络
I need class that has singleton behaviour. What\'s the difference between usin开发者_StackOverflow社区g the Singleton module...

I need class that has singleton behaviour.

What's the difference between usin开发者_StackOverflow社区g 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号