I am implementing factory pattern Here is my factory class:
class ProductFactory
{
private HashMap m_RegisteredProducts = new HashMap();
public void registerProduct (String productID, Class productClass)
{
m_RegisteredProducts.put(productID, productClass);
}
public Product createProduct(String productID)
{
Class productClass = (Class)m_RegisteredProducts.get(productID);
Constructor productConstructor = cClass.getDeclaredConstructor(new Class[] { String.class });
return (Product)productConstructor.newInstance(new Object[] { });
}
}
and here is my concrete class:
class OneProduct extends Product
{
static {
Factory.instance().registerProduct("ID1",OneProduct.class);
}
...
}
My Question:
-
how do I enforce all the concrete implementations to register an ID along with their class object? - Because if the class doesn't register itself like this in the factory then it cant be used.
-
Can't I use an abstract class which requires somehow all its child to send its name and id to the parent, enforcing this constraint? Something like this:
public abstract class Product { public Product(String name, Class productClass){ } }
Am I missing anything here?
Aucun commentaire:
Enregistrer un commentaire