ruby - create singleton with parameters?

前端 未结 5 920
情深已故
情深已故 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:59

    This was too long to put into a comment (e.g. stackoverflow said it was too long)

    Ok so here's what I came up with:

    class MyLogger
      @@singleton__instance__ = nil
      @@singleton__mutex__ = Mutex.new
      def self.config_instance file_name
        return @@singleton__instance__ if @@singleton__instance__
        @@singleton__mutex__.synchronize {
          return @@singleton__instance__ if @@singleton__instance__
          @@singleton__instance__ = new(file_name)
          def self.instance
            @@singleton__instance__
          end
          private_class_method :new
        }
        @@singleton__instance__
      end
      def self.instance
        raise "must call MyLogger.config_instance at least once"
      end
      private
      def initialize file_name
        @file_name = file_name
      end
    end
    

    This uses 'config_instance' to create and configure the singleton instance. It redefines the self.instance method once an instance is ready.

    It also makes the 'new' class method private after creating the first instance.

提交回复
热议问题