ruby - create singleton with parameters?

前端 未结 5 974
情深已故
情深已故 2021-02-05 08:17

I\'ve seen how to define a class as being a singleton (how to create a singleton in ruby):

require \'singleton\'

class Example
  include Singleton
end
         


        
5条回答
  •  悲哀的现实
    2021-02-05 09:08

    Here's another way to do it -- put the log file name in a class variable:

    require 'singleton'
    class MyLogger
      include Singleton
      @@file_name = ""
      def self.file_name= fn
        @@file_name = fn
      end
      def initialize
        @file_name = @@file_name
      end
    end
    

    Now you can use it this way:

    MyLogger.file_name = "path/to/log/file"
    log = MyLogger.instance  # => #
    

    Subsequent calls to instance will return the same object with the path name unchanged, even if you later change the value of the class variable. A nice further touch would be to use another class variable to keep track of whether an instance has already been created, and have the file_name= method raise an exception in that case. You could also have initialize raise an exception if @@file_name has not yet been set.

提交回复
热议问题