View RSS Feed

Design Patterns

Class Registration - using reflection

Rate this Entry
by , 03-09-2012 at 07:11 PM (2325 Views)
Registration of the new product class could be done to the factory in case you use reflection (e.g in .NET languages or Java), without making any change in factory itself.Without being aware of the object type for creation of the objects in factory class, a map is kept b/w class type and productID. In this particular case, when new product gets added to the application then it shall be made registered to factory. No change is required in factory class code for this kind of operation.
Java Code:
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[] { });
	}
}

Submit "Class Registration - using reflection" to Facebook Submit "Class Registration - using reflection" to Digg Submit "Class Registration - using reflection" to del.icio.us Submit "Class Registration - using reflection" to StumbleUpon Submit "Class Registration - using reflection" to Google

Comments