[英]How to initialise an instance other than the current class in Ruby?
I want to initialize instances of different class based on the initial params. 我想基于初始参数初始化不同类的实例。 For example, I want to have different behavior for Hello.new(true)
and Hello.new(false)
. 例如,我想对Hello.new(true)
和Hello.new(false)
有不同的行为。 Be precise, I want them to create instance of different classes . 确切地说,我希望他们创建不同类的实例 。
How could I achieve that in Ruby? 我怎么能在Ruby中实现这一点?
class Name1
end
class Name2
end
class Hello
def initialize(opts)
if opts
Name1.new
else
Name2.new
end
end
end
What you are talking about is called Factory
pattern (at least, a simple version). 你所说的是Factory
模式(至少是一个简单的版本)。 It's possible to split the new
process invoking allocate
and initialize
manually, but I don't recommend it. 可以将new
进程拆分为手动allocate
和initialize
,但我不推荐它。
The main reason is because it totally counter-intuitive. 主要原因是因为它完全违反直觉。 You'll (almost) never find a Ruby library behaving like this. 你(几乎)永远不会发现Ruby库表现得像这样。
Instead, I suggest you to use a different method. 相反,我建议你使用不同的方法。 For example, #factory
. 例如, #factory
。
class Name1
end
class Name2
end
class Hello
def self.factory(opts)
klass = if opts
Name1
else
Name2
end
klass.new
end
end
Hello.factory(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.