I've been reading the GoF patterns book and I'm wondering if using generics would achieve the same results as using the prototype pattern's conventional clone implementation. Maybe I'm not understanding the prototype pattern correctly so let me know if what's happening there is not the prototype pattern.
As far as I understand the prototype pattern is basically instead of creating different factories for different subclasses u pass the subclass to the factory in the constructor so that it instantiates the subclasses from that blueprint.
In the below example I set the type of objects this factory should return as a generic and instantiate it when calling make item.
Example:
public class PrototypedFactory {
Prototype prototype;
public PrototypedFactory(Prototype prototype) {
this.prototype = prototype;
}
public Prototype makeItem() throws CloneNotSupportedException {
return (Prototype) prototype.clone();
}
public static void main(String[] args) throws Exception {
GenericFactory<ConcretePrototype> factoryGeneric = new GenericFactory<ConcretePrototype>(
ConcretePrototype.class);
PrototypedFactory factory = new PrototypedFactory(new ConcretePrototype());
Prototype item = factory.makeItem();
Prototype item2 = factoryGeneric.makeItem();
System.out.println(item.getName());
System.out.println(item2.getName());
}
}
GenericFactory:
public class GenericFactory<T extends Prototype> {
Class<T> c;
public GenericFactory(Class<T> clazz) {
c = clazz;
}
public Prototype makeItem() throws Exception {
return c.newInstance();
}
}
Prototype:
public abstract class Prototype implements Cloneable {
String name = "prototype";
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public String getName() {
return name;
}
}
Aucun commentaire:
Enregistrer un commentaire