Factory design pattern using reflection involves storing (registering) various type names with their corresponding class type in a hash table, then using this hash table for generating objects in the factory.
interface Product
{
void foo();
}
class ProductFactory
{
HashTable m_RegisteredProducts = new HashTable();
public void registerProduct(string productID, Type p) {
m_RegisteredProducts.add(productID, p);
}
public Product createProduct(string productID){
return (Product) new m_RegisteredProducts[productID];
}
}
I'm not clear on when does the process of registering a new type happen since all types to be used are to be loaded into the hash table at runtime. Where is the call to registerProduct() to be made?
- Calling registerProduct() for all different classes at a single place inside ProductFactory class doesn't make sense since it would defeat the purpose of using reflection over naive switch/case method.
- If registerProduct() is called inside the class definition of all classes implementing the interface, then an instance if the class is created after/using the Factory hence will always give an error.
Aucun commentaire:
Enregistrer un commentaire