java - Specifying which subclass in super class constructor -


i trying first populate list of generic objects , later instantiate them, , when instantiating them, specify of objects each is.

the use-case working on reading data file , constructing map, has various interactable objects. type of interactable each object is stored in it's own data file directed map's data file. code example:

in reading map:

    if ((char)map[i][j] == '*')            mapobjects.add(new mapobject()); 

and afterward:

    (int = 0 ; < mapobjects.size() ; i++)             mapobjects.set (i, new mapobject(in.readline()));              //in.readline gives path file 

in mapobject's constructor:

    public mapobject (string in){     try{         bufferedreader br = new bufferedreader(new filereader("src/data/" + in + ".txt"));         int temp = integer.parseint(br.readline());         if (temp == 0)             = new door (); //this apparently not allowed              /*continue instantiate door's fields data file*/     } 

and door class:

    public class door extends mapobject {         public door () {}     } 

i realize isn't best way solve problem, raised curiosity doesn't work. there way this? have super's constructor choose subclass be?

what want abstract factory pattern.

briefly...

it's poor design have superclass know subclasses, it's ok have separate class knows both.

the abstract factory defines factory method returns abstract type (an interface or superclass - in case mapobject) , method decides exact class returned based on parameters method.

a simple example be:

public class mapobjectfactory {      public mapobject create(int i) {         if (i == 0)             return new door();         if (i == 1)             return new othersubclass();         // etc, "default" in case above conditions not met         return new mapobject();     } } 

then invoke:

mapobjectfactory factory = new mapobjectfactory();  mapobject m = factory.create(integer.parseint(br.readline())); 

you make create() method static avoid having create instance of mapobjectfactory invoke stateless method:

mapobject m = mapobjectfactory.create(integer.parseint(br.readline())); 

but couldn't swap in implementation @ runtime in case wanted make selection criteria dynamic. in case you'd make factory class implement interface , make load using class name example (or have abstract factory abstract factory!).


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -