From: Trans Date: 2006-09-28T10:15:10+09:00 Subject: Multi-Module Alternative to the Factory Pattern? I've been using a factory pattern for a set of packaging classes --classes that generate different package formats (eg. Debian, RPM, etc.), but it's not quite the right fit b/c it leads to repetition of the staging step. Yuk! So I think a better fit is to have one class (Packager) that calls on external modules (or classes) for each different format. But, unfortuately there are quite a few attributes needed by each from the Packager, and it's just doesn't seem right to pass that many variables. So it seems like it would be better to just include the needed module into the Packager class as needed. But here again I can't un-include a format module once done with it in order to use another format. So I'm right back to using a factory pattern. Then I had this idea. and I'm wondering what others think of it. First we need this little extension from Facets: class Object # Like super but skips to a specific ancestor module or class. # # class A # def x ; 1 ; end # end # # class B < A # def x ; 2 ; end # end # # class C < B # def x ; superior(A) ; end # end # # C.new.x #=> 1 # def superior(klass=self.class.superclass, *args, &blk) unless self.class.ancestors.include?(klass) raise ArgumentError end called = /\`([^\']+)\'/.match(caller(1).first)[1].to_sym klass.instance_method(called).bind(self).call(*args,&blk) end end Then: module Debian def pack ; "Debian package"; end end module RPM def pack ; "RPM package"; end end class Packager include Debian, RPM def pack( type ) superior(type) end end pkgr = Packager.new pkgr.pack(Debian) #=> "Debian package" pkgr.pack(RPM) #=> "RPM package" What do you think? Thanks, T.