ruby - 用参数创建单例? [英] ruby - create singleton with parameters?

查看:61
本文介绍了ruby - 用参数创建单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了如何将类定义为单例(如何在 ruby​​ 中创建单例):

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

但是,如果我想为该单个实例提供一些参数,这意味着该示例应该始终初始化某些属性,该怎么办.例如,假设我有一个类的唯一目的是登录到一个文件(这只是一个例子),但它需要一个文件名才能工作.

But what if I want to give it some parameters for that single instance, meaning, the Example should always have certain properties initialized. For example, say I had a class whose sole purpose is to log to a file (this is just an example) but it requires a name of a file to log to before it can work.

class MyLogger
  def initialize(file_name)
    @file_name = file_name
  end
end

如何使 MyLogger 成为单例但确保它获得文件名?

How can I make MyLogger a singleton but make sure it gets a file_name?

推荐答案

Singleton 不提供此功能,但您可以自己编写代替使用单例

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.

此代码强制您使用 MyLogger.instance 或至少在第一次调用时使用,如果您知道它将是第一次调用.

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

这篇关于ruby - 用参数创建单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆