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:

  1. how enforce concrete implementations register id along class object? - because if class doesn't register in factory cant used.

  2. 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

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -