0

是否可以在 Ruby 中基于单例类定义一个新的非单例类?

我尝试了这样的事情(片段):

module SomeModule
  extend self
  class Singleton;end
end

class NonSingleton
  include SomeModule
end
nonsingleton = NonSingleton.new

但是,当然对你们大师来说,这已经很明显了,这不会像我预期的那样起作用。

基本上我想要的是重用 Singleton 类的功能,而不以任何方式影响它的行为。可能吗?

经过进一步调查,这似乎根本不可能(如果我错了,请纠正我)。像跟随这样的黑客会太丑陋/凌乱吗?

singleton = File.read('some_singleton.rb')
non_singleton = eval(singleton.gsub('include Singleton', ''))
# Or perhaps:
non_singleton = eval(singleton.gsub('module SomeModule', 'module MyOwnModule'))
4

1 回答 1

1

好的。我这里没有真正的红宝石,只有 IronRuby,但是当我尝试这样做时会发生这种情况:

# define a new object
>>> s = "hello"
=> "hello"

# add a method to it's singleton class
>>> class << s
... def say; puts self; end
... end
=> nil

# get it's singleton class
>>> SingletonBaseClass = class << s; self; end
=> #<Class:#<String:0x000005c>>

# try build a new one inheriting from the singleton class
>>> class NonSingletonClass < SingletonBaseClass
... end
:0: can't make subclass of virtual class (TypeError)

IronRuby 与普通的 ruby​​ 语言本身相当兼容,我敢打赌,在真正的 ruby​​ 中也会发生类似的错误消息。简而言之,你做不到。

这就引出了一个问题:你想做什么?如果特定对象的单例类变得足够复杂以至于您想重用它,那么您不应该将该代码放在常规类或模块中吗?

例如,您可以这样做:

# define our reusable code
module SharedMethods
  def a;end
  def b;end
  # and so on
end

# mix it into the singleton of some object
s = "hello"
class << s; include SharedMethods; end

然后您可以在任何其他对象/类/等上重新使用它

于 2009-03-17T21:29:11.863 回答