Re: Problem implementing an object factory
On Sep 9, 4:01 am, Barry <dhb2...@gmail.com> wrote:
Stephen Torri wrote:
On Sat, 08 Sep 2007 11:15:25 +0800, Barry wrote:
[...]
Is there a way to have each class that will be a part of a
object factory automatically register itself?
it depends on how you define "automatically",
if you meant register as you write the class, I think there's not.
if you meant easier registering, maybe you can apply macro, then you can
write less code, but since your code is not so complicated and the
reg/unreg is clean and easy to use, moreover, the macro is so notorious,
so don't fix it if it ain't broken.
If he means that the user of the factory doesn't have to do
anything, the usual solution is to use the singleton idiom for
the factory (to avoid problems in order of initialization), and
then use static objects to register the the factories with the
map; if the map maps to functional objects, rather than to
pointers to functions, you need a static object for each type
anyway, so you might as well put the registration code in the
constructor.
An alternative solution would be to simply use a staticly
initialized table of pointers, using std::find_if to find the
factory. This is particularly good if the factories are
functions, and not functional objects, since it means that the
dynamic factory is entirely staticly initialized, and can be
used from constructors of other static objects without order of
initialization worries. If you do this, I would suggest using
some sort of automatic code generation for the table, so that
you don't have to re-edit it (with the risk of forgetting to do
so) each time you add a function. (And of course, it means that
the user of the dynamic factory can't add additional functions
of his own. Depending on what you're using the dynamic factory
for, this can be an advantage or a disadvantage.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34