factory pattern
Ruby
code posted
created at 29 Mar 20:04, updated at 31 Mar 12:00
Edit
|
Back
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Vehicle def initialize(options); @options = options; end def self.factory(options) options.delete("class").new(options) end end class Bicycle < Vehicle; def honk; "Ring Ring"; end end class Train < Vehicle; def honk; @options["tone"] || "Woooooooo Woooooooo"; end end irb> Vehicle.factory("class" => Bicycle).honk => "Ring Ring" irb> Vehicle.factory("class" => Train, "tone" => "squeek").honk => "squeek" |
439 Bytes in 2 ms with coderay