From: Joel VanderWerf Date: 2006-12-03T10:27:29+09:00 Subject: Re: Factory pattern, abstract base class Daniel Berger wrote: > Hi all, > > I'm trying to setup an abstract base class as a factory for its > subclasses. The below code fails, as it always returns an instance of > Foo::Bar instead of one of its subclasses. > > module Foo > class Bar > def initialize(arg) > return if self.class != Foo::Bar > case arg.downcase > when 'baz' > return Baz.new(arg) > when 'zap' > return Zap.new(arg) > end > end > end > > class Baz < Bar > end > > class Zap < Bar > end > end > > fb = Foo::Bar.new('baz') > p fb # Returns Foo::Bar, but I want Foo::Baz > > Perhaps my whole approach is wrong. What is the proper way to achieve > what I'm after (without resorting to making Bar a module)? module Foo class Bar def self.new(arg) return super() if self != Foo::Bar case arg.downcase when 'baz' return Baz.new(arg) when 'zap' return Zap.new(arg) end end end class Baz < Bar end class Zap < Bar end end fb = Foo::Bar.new('baz') p fb # ==> # -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407