我很好奇这是如何运作的。例如,如果我创建一个基于工厂模式的类,您可以在其中“注册”类以供以后使用,然后执行类似的操作
FactoryClass.register('YourClassName', [param, param, ...]);
FactoryClass.create('your_class_name').call_method_from_this_object
where 'class_name'
是映射到值的哈希中的键:ClassName
有没有类似的东西PHP反射 http://php.net/manual/en/book.reflection.php,我可以在哪里根据字符串名称创建类的实例并传入参数? (在 php 中,参数将是一个数组,然后 php 知道如何处理)
因此,如果我们举一个现实世界的例子:
class Foo
attr_reader :something
def initialize(input)
@something = input
end
def get_something
return @something
end
end
# In the factory class, foo is then placed in a hash: {'foo' => 'Foo'}
# This step might not be required??
FactoryClass.create('Foo', ['hello'])
# Some where in your code:
FactoryClass.create('foo').get_something # => hello
这可以在红宝石中做到吗?我知道一切本质上都是一个对象,但我还没有看到任何关于从像这样的字符串名称创建类实例以及传入对象的 API 或文档。
至于上面的哈希,现在考虑一下我可能必须这样做:
{'foo' => {'class' => 'Foo', 'params' => [param, param, ...]}}
这样当你打电话时.create
on the FactoryClass
它会知道,好吧我可以实例化Foo
以及相关的参数。
如果我离基地很远,请随时教育我。