[英]How to initialise an instance other than the current class in Ruby?
我想基於初始參數初始化不同類的實例。 例如,我想對Hello.new(true)
和Hello.new(false)
有不同的行為。 確切地說,我希望他們創建不同類的實例 。
我怎么能在Ruby中實現這一點?
class Name1
end
class Name2
end
class Hello
def initialize(opts)
if opts
Name1.new
else
Name2.new
end
end
end
你所說的是Factory
模式(至少是一個簡單的版本)。 可以將new
進程拆分為手動allocate
和initialize
,但我不推薦它。
主要原因是因為它完全違反直覺。 你(幾乎)永遠不會發現Ruby庫表現得像這樣。
相反,我建議你使用不同的方法。 例如, #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.