Factory Design Pattern with Java generics
I was wondering if it was possible to implement the factory pattern using a generic like sintax with java5. Something like:
IFactory factory = new ConcreteFactory();
Car c=factory.CreateObject<Car>();
I saw this article the other day http://weblogs.asp.net/pgielens/archive/2004/07/01/171183.aspx
done in C# for the framework 2.0 and tryed to re-implement it with java5 however I was less then fortunate, can someone do a functional conversion?
> > Object theObject = Class.forName( className
> > ).newInstance() ;
>
> What's the point of using a generic factory if one
> can't avoid using Object :)
You can avoid using Object. You could just as easily use a common base or interface to implement you factories create method.
i.e somehting along these lines.
public Car createCar( String className)
{
return (Car) Class.forName( className ).newInstance() ;
}
I usually also use a Properties or XML file to map abstract names to actual class names in my factory.
I had to change the signature a bit but this is the best I came with:
(I don't like I have to write Type.class but if someone has a better idea please share, I deliberatly used classes are return types but you can easily program to the interfaces as well)
use:
ConcreteFactory cf=new ConcreteFactory();
Car c=cf.Create(Car.class);
public interface Vehicle {
String getName();
}
public class Plane implements Vehicle {
String name="Mig 29";
public String getName() {
return name;
}
}
public class Car implements Vehicle {
String name="Volvo";
public String getName() {
return name;
}
}
public interface IFactory{
<T> T Create(Class<T> type);
}
public class ConcreteFactory implements IFactory {
public <T extends Vehicle> T Create(Class<T> type) {
try {
return type.newInstance();
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
}
}
}