java - Implementing Factory Pattern with reflection -
i implementing factory pattern here 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 concrete class:
class oneproduct extends product { static { factory.instance().registerproduct("id1",oneproduct.class); } ... }
my question:
how enforce concrete implementations register id along class object? - because if class doesn't register in factory cant used.
can't use abstract class requires somehow child send name , id parent, enforcing constraint? this:
public abstract class product { public product(string name, class productclass){ } }
am missing here?
in java 8 write
class productfactory { private final map<string, function<string, product>> m_registeredproducts = new hashmap<>(); public productfactory registerproduct (string productid, function<string, product> productfactory) { m_registeredproducts.put(productid, productfactory); return this; } public product createproduct(string productid) { return m_registeredproducts.get(productid).apply(productid); } }
to register
static { factory.instance().registerproduct("id1", oneproduct::new) .registerproduct("id2", s -> new oneproduct("my" + s)); .registerproduct("id3", s -> { throw new assertionerror("never create " + s); }); }
the oneproduct::new
same s -> new oneproduct(s)
or
new function<string, product>() { public product apply(string s) { return new oneproduct(s); } }
note(1): java 8 ensure have visible oneproduct(string)
constructor or fail compile.
note(2): java 7 end of public support.
Comments
Post a Comment