ruby - create singleton with parameters?

前端 未结 5 917
情深已故
情深已故 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 08:54

    Singleton does not provide this functionality, but instead of using singleton you could write it by yourself

    class MyLogger
      @@singleton__instance__ = nil
      @@singleton__mutex__    = Mutex.new
    
      def self.instance(file_name)
        return @@singleton__instance__ if @@singleton__instance__
    
        @@singleton__mutex__.synchronize do
          return @@singleton__instance__ if @@singleton__instance__
    
          @@singleton__instance__ = new(file_name)
        end
        @@singleton__instance__
      end
    
      private
    
      def initialize(file_name)
        @file_name = file_name
      end
      private_class_method :new
    end
    

    It should work, but I did not tested the code.

    This code forces you to use MyLogger.instance or at least at the first call if you know it will be first time calling.

提交回复
热议问题