vendredi 3 mai 2019

Pattern/structure for classes with the same methods but different parametrs

For example, I develop a grapher, where have two classes:

Function (like 3x+1)

Equation (like x^2+y^2<1)

They have many methods with the same name and same return type, but different input parameters. And also some unique methods. So, I have an array where I store functions and equations together. When I draw its, move, etc I must use if/switch to determine the type. Is there any better solution?

This is example of such code:

interface Grapher {
    //it is empty
}

class GrapherFunction implements Grapher {
    //...some code...

    ArrayList<Point> draw(double left, double right) {...}
    double move(double vx) {...}
}

class GrapherEquation implements Grapher {
    //...some code...

    ArrayList<Point> draw(double left, double right, double bottom, double top) {...}
    double move(double vx, double vy) {...}

    double square() {...}
}


main() {
    //...
    Grapher[] graphs = ...; //store GrapherFunction and GrapherEquation
    for (var graph : graphs)
        if (graph instanceof GrapherFunction)
            graph.draw(0, 1);
        else
            graph.draw(0, 1, 2, 3);
}

PS methods in class Function have completely different realization than in class Equation

Aucun commentaire:

Enregistrer un commentaire