What is the correct way to write a singleton pattern in Ruby?

前端 未结 3 1022
心在旅途
心在旅途 2021-01-30 11:31

I\'m trying to write the most secure singleton in Ruby that I can. I\'m new to the language, which is so elastic that I don\'t have a strong feeling that my singleton class wil

3条回答
  •  旧时难觅i
    2021-01-30 11:52

    If you want to create a singleton, why bother creating a class? Just create an object, and add the methods and instance variables to it you want.

    >> MySingleton = Object.new
    => #
    >> MySingleton.instance_eval do
    ?>   @count = 0
    >>   def next
    >>     @count += 1
    >>   end
    >> end
    => nil
    >> MySingleton.next
    => 1
    >> MySingleton.next
    => 2
    >> MySingleton.next
    => 3
    

    A more standard way that people implement this pattern is to use a Module as the singleton object (rather than the more generic Object):

    >> module OtherSingleton
    >>   @index = -1
    >>   @colors = %w{ red green blue }
    >>   def self.change
    >>     @colors[(@index += 1) % @colors.size]
    >>   end
    >> end
    => nil
    >> OtherSingleton.change
    => "red"
    >> OtherSingleton.change
    => "green"
    >> OtherSingleton.change
    => "blue"
    >> OtherSingleton.change
    => "red"
    

    If you wanted your singleton object to inherit from some class, just make it an instance of that class. To inherit from a mixin, just use #extend. If you want a singleton object, ruby makes it really easy, and unlike other languages, it doesn't have to be defined in a class.

    Ad-hoc singletons (my first example) are all over the place, and cover the majority of cases I've encountered. The module trick normally covers the rest (when I want something a little more formal).

    Ruby code should (imho) use duck typing (via #respond_to?) rather than explicitly checking an object's class, so I normally don't care about the uniqueness of my singleton objects' class, since it's not its class that makes it unique, but everything I added after.

提交回复
热议问题