我有一個類,L從一個庫,只能通過工廠方法實例化,L.factory。我希望能夠通過繼承進行專門化。所以我們有:如何在Ruby中專門化只能通過工廠實例化的類?
class L
attr_accessor :g
def self.factory
l = L.new
l.g = "magic"
l
end
end
class S < L
def self.new
allocate
l = L.factory
# is there a way to return a class S object here with data from l?
end
def g2
"my #{g}"
end
end
s = S.new
s.g #==> "magic"
s.g2 #==> fails because s.class is L
爲什麼不使用委託而不是繼承?讓S有一個L並委託所有的方法,除了你提供的方法。 [SimpleDelegator](http://www.ruby-doc.org/stdlib-2.0.0/libdoc/delegate/rdoc/SimpleDelegator.html)使這種事情變得簡單 – dbenhur