Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I've implemented a generic factory as described here

I need to register elements to the factory hard-code like this:

Factory.Register(1, typeof(MyClass));

this factory will have to be correlated with a simple domain data type table [id,Display], in this case id 1 is related to MyClass.

I was thinking to add a column to that table with the qualified type, so I can simply retrieve the id to types. table will be [id,Display, typeName]

and I will use the factory like this:

Factory.Register(id, Type.GetType(typeName));

I tried it and it's working ok.

is this a good design?

are there any security flaws?

is there a better way to do things?

share|improve this question
add comment

2 Answers 2

up vote 2 down vote accepted

This ties the db design to the programming language, which, in my opinion, is something you would want to avoid.

A simple alternative would be to add a key to the table and have a way to map that key to a type in the programming language of your choice. This may not be such an elegant solution as it may require a switch statement, but it is the better architecture despite the shortcomings of my suggested implementation. This way if you have to use the table in another language, you will be ok.

At the very least, add the language agnostic key to your current table and add a cross reference to your fully qualified type name.

share|improve this answer
add comment

For a Factory design pattern it is fundamental that the knowledge of the mapping between an id and the corresponding class is only handled by the Factory. Instead in the example given it seems that the caller is aware of the mapping. I would encapsulate this knowledge within the Factory pattern, hard-coded.

If you don't want this knowledge to be hard-coded, i.e. you want to give the mapping after having implemented the Factory class, you can provide the mapping as a configuration file and let the Factory class use computational reflection to handle instantiation of the class whose name is given as a string into the file.

share|improve this answer
    
that's kind of what I suggested, isn't it? –  Mithir Feb 9 '12 at 6:37
    
mmh, let me say in this way: the caller of Factory.Register(...) should not indicate the mapping, instead the Factory itself can do it, and even at runtime. –  emit Feb 9 '12 at 12:47
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.