|
![](/i/fill.gif) |
I have noticed that whenever I wind up using the Factory pattern, I wind up
with a listing of all the classes somewhere in a central place, namely the
factory method that instantiates the appropriate class. It seems to me this
kind of defeats the entire purpose of the method.
I would suggest a language feature to overcome this.
A class can be marked "factory" and if it has no parent classes that are
marked factory, then it is abstract, but one is allowed to invoke "new" on
the class.
If "new XYZ(alpha, beta)" is invoked and XYZ is a factory class, then all
other (loaded) classes marked "factory" with a parent of "XYZ" are
inspected. They are inspected in a breadth-first manner (with individual
nodes at the same level being invoked in an undefined order), except that
the most-derived classes are invoked before the less-derived classes. I.e.,
breadth-first, but starting from the leaves. Each compatible constructor is
invoked, and the first one that doesn't throw an exception is the one used.
If all throw an exception, then the original "new" statement throws an
exception.
Potential problems: Getting the order right. The overhead of throwing
exceptions (would be better if they could return a null, for example).
Defining how this might work for languages without metadata. Figuring out
the right semantics if one of the child classes is in a dynamically-loaded
library that's not currently in a state in which its elements can be invoked
(i.e., not loaded from disk yet, uninitialized, etc). Do we have to allocate
enough memory for the biggest child class to be filled in? Do we reallocate
memory each time we try a child?
Benefits: You can extend an abstract class without needing to have a static
factory method. There would be no need for a central list of subclasses of a
particular class (which is what dynamic dispatch was supposed to avoid in
the first place).
Thoughts?
--
Darren New, San Diego CA, USA (PST)
Linux: Now bringing the quality and usability of
open source desktop apps to your personal electronics.
Post a reply to this message
|
![](/i/fill.gif) |