如何在 X 类工厂中声明方法,以便其子工厂可以使用 sub-类 Class-1 常量?

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

我有一个 MapFactory,它是一个抽象 class 实现了子工厂之间的共享方法 classes Map1Creator, Map2Creator, Map3Creator, ..., MapNCreator 这些 nCreators return 一个 Map1(它扩展了一个 Map class),它已经用 classes MapN 中的常量进行了初始化。 我的教授要求使用工厂模式而不是构造函数,所以我不得不在我的 MapN classes 中删除它们。

地图class:

public abstract class Map {

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

在子class Map1 中(字符串,因为它们将从文件中读取):

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";

}

在MapFactory中无法指定只有一种MapN的方法,所以只能写非指定的方法:

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;
    }
}

因此在 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 
    }

但是如您所见,"m" 映射具体是一个 Map1,并且方法需要 Map1 class 中的常量。如果我在 MapFactory 中声明这些方法,它会在 MapNCreators 中给我一个错误,因为它们无法从 Map 转换为 MapN(我认为多态性会涵盖这个......)。 有没有办法在 "father" 工厂 class 中声明方法,以便任何子创建者 class 都可以将它们用于自己的类型?

答案,一年后:在父class里面做一个泛型return/parameter类型:

<T extends Map> or <? extends Map>