Ruby中的工厂方法 [英] Factory methods in Ruby
问题描述
让单个构造函数返回适当类型的对象的最巧妙,最类似于Ruby的方法是什么?
更具体地说,这是一个虚拟示例:假设我有两个类 Bike
和 Car
,它们是 Vehicle
的子类.我想要这个:
To be more specific, here's a dummy example: say I have two classes Bike
and Car
which subclass Vehicle
. I want this:
Vehicle.new('mountain bike') # returns Bike.new('mountain bike')
Vehicle.new('ferrari') # returns Car.new('ferrari')
我在下面提出了一个解决方案,但是它使用了 allocate
,这似乎过于实现.还有什么其他方法,或者我真的可以吗?
I've proposed a solution below, but it uses allocate
which seems way too implementation-heavy. What are some other approaches, or is mine actually ok?
推荐答案
如果我创建的工厂方法未被称为 1 new
或 initialize
,我想这并不能真正回答如何构造...构造函数..."的问题,但是我认为这就是我的解决方法……
If I make a factory method that is not called1 new
or initialize
, I guess that doesn't really answer the question "how do I make a ... constructor ...", but I think that's how I would do it...
class Vehicle
def Vehicle.factory vt
{ :Bike => Bike, :Car => Car }[vt].new
end
end
class Bike < Vehicle
end
class Car < Vehicle
end
c = Vehicle.factory :Car
c.class.factory :Bike
1.在本示例示例中,调用方法 factory 确实非常有效,但是IRL您可能需要考虑 @AlexChaffee 在评论中的建议.
1. Calling the method factory works really well in this instructional example but IRL you may want to consider @AlexChaffee's advice in the comments.
这篇关于Ruby中的工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!