java - Create instances using one generic factory method -


i trying find easy extend way create objects @ runtime based on static string class attribute, called name.

how can improve code, uses simple if construct?

public class flowerfactory {  private final garden g;  public flowerfactory(garden g) {   this.g = g; }  public flower createflower(final string name) {     flower result = null;     if (rose.name.equals(name)) {        result = new rose(g);    } else if (oleander.name.equals(name)) {        result = new oleander(g);    } else if ... { ... } ...     return result; } 

newinstance() can not used on these classes, unless remove constructor argument. should build map (map) of supported flower class references, , move contructor argument property setter method, or there other simple solutions?

background information: goal implement kind of 'self-registering' of new flower classes, flowerfactory.getinstance().register(this.name, this.class), means answers far introspection-based solutions fit best.

you can use reflection despite having constructor argument:

rose.class.getconstructor(garden.class).newinstance(g); 

combined static name class mapping, implemented this:

// todo handle unknown name flowers.get(name).getconstructor(garden.class).newinstance(g); 

where flowers populated in static initializer block:

static {   map<string, class<? extends flower>> map = new hashmap<string, class<? extends flower>>();   map.put(rose.name, rose.class);   // add flowers   flowers = collections.unmodifieablemap(map); } 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -