dimanche 7 juin 2015

How to declare methods in a ClassX factory so that its sub-factories can use sub-classes ClassX-1 constants?

I have a MapFactory, which is an abstract class that implements the shared methods among the sub-factory classes Map1Creator, Map2Creator, Map3Creator, ..., MapNCreator These nCreators return a Map1(which extends a Map class) which has been initialized with the constants in the classes MapN. My professor asked to use a factory pattern instead of constructors, so I had to remove them among my MapN classes.

The Map class: public abstract class Map {

protected Sector[][] grid;
protected List<Integer> dangerousSectCoord ;
protected List<Integer> normalSectCoord;
//[...]
protected List<Integer> emptySectCoord;
//all the getters...

}

While in the subclass Map1 (the strings because they'll be read from file):

public class Map1 extends Map{
private final static int ROWS_NUMBER=14;
private final static int COLS_NUMBER=23;
private final static String normSectorString= "all the sectors...";
private final static String dangerousSectorString [......]
private final static String escapeSectorString="B10,F01,P01,V11";

}

In the MapFactory I can't specify methods with only one kind of MapN, so I can only write non-specific methods:

public abstract class MapFactory {
public abstract Map createMap();
//here there should be 
//assignSectors(Map m);
//setDimensions(Map m);
//but MapN can't be converted to Map and in the MapNCreator Eclipse
//reminds me that I must implement the father's methods

public List<Integer> mapStrings(String string){
    List<Integer> coor=new ArrayList<Integer>();
    //parse sub-classes strings and convert them to coordinates;
}

}

So in the MapNCreator:

public class Map1Creator extends MapFactory{
public Map1 createMap(){
    Map1 m= new MapGalvani();
    setDimensions(m)
     assignSectors(m);
    return null;
 }
public void setDimensions(Map1 m ) {
      m.grid= new Sector[m.getRowsNumber()][m.getColsNumber()];
    m.alienSectCoord=new ArrayList<Integer>();
    //[...]
    m.emptySectCoord=new ArrayList<Integer>();
}

public void assignSectors(Map1 m){
//parse those constant strings and put them in the grid
//m.constantStringNormalSectors 
}

But as you can see the "m" map is specifically a Map1 and the methods need the constants inside the Map1 class. If I declare those methods in the MapFactory it gives me an error in the MapNCreators, as they cannot convert from Map to MapN (I thought polymorphism would cover this...). Is there a way to declare methods in a "father" factory class so that any sub-creator class will be able to use them with their own type?

Aucun commentaire:

Enregistrer un commentaire