Ruby中的工厂方法 [英] Factory methods in Ruby

查看:59
本文介绍了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屋!

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