Search code examples
javagenericsgraphfactory-pattern

Factory pattern when the abstract product is generic class


the first part of my project is to construct an hypergraph

This is a quickly-drew UML diagram enter image description here

Vertex class

public abstract class Vertex <T>{

    int vertexId ;
    T vertexValue ;
    public  abstract  T computeVertexValue();
}

Imagevertex Class

public class ImageVertex extends Vertex<Map<String, Instance>>{


    public ImageVertex(int id ) {
        this.vertexId=id;
    }

    @Override
    public Map<String, Instance> computeVertexValue(){
        return null;
    }
}

AbstractVertexFactory

public abstract class AbstractVertexFactory {

    public abstract  Vertex createVertex(int id);

    public  Vertex produceVertex(int id) {

        Vertex vertex = createVertex(id);
        vertex.computeVertexValue();
        return vertex;
    }
}

ImageFactory class

public class ImageFactory extends AbstractVertexFactory {

    @Override
    public Vertex createVertex(int id) {
        // TODO Auto-generated method stub
        return new ImageVertex(id);
    }
}

Simulator

public class ImageFactorySimulator {

    /**
     * @param args
     */
    public static void main(String[] args) {


        AbstractVertexFactory imFactory= new ImageFactory();

        ImageVertex im = (ImageVertex) imFactory.createVertex(0);

    }

}

the use of cast in the simulator is boared How can I avoid it ?


Solution

  • You could use

    public abstract class AbstractVertexFactory <T extends Vertex> {
        public abstract  T createVertex(int id);
    }
    

    And

    public class ImageFactory extends AbstractVertexFactory<ImageVertex> {
    
        @Override
        public ImageVertex createVertex(int id) {
            // TODO Auto-generated method stub
            return new ImageVertex(id);
        }
    }