mercredi 11 décembre 2019

Factory of objects of the same type but with different parameters

I've got some code which adds in some new objects into a background, some of the code for this is here (I've got 27 separate lines like this in total) :

background.add(new Obstacle("/car1Left.png", 400, 597, -1, 50, 50));
background.add(new Log("/logs.png", 300, 400, 276, -2));
background.add(new Log("/log3.png", 150, 490, 329, 0.75));
background.add(new Turtle(300, 376, -1, 130, 130));
background.add(new WetTurtle(700, 376, -1, 130, 130));

As you can see it's not exactly efficient so I wanted to make a factory of this instead, I've started making it and it works for now but I've a slight issue. All of these objects (Obstacle, Log, Turtle etc) extend the Actor class, so they're all essentially Actors. In some of them some of the parameters do not change at all (e.g. when adding a new obstacle, the last 2 values in the constructor (50) stay the same for all, so i'd imagine I could just put it in as the default value for that case, but i'm not entirely sure on how to handle the variables that change.

Currently, what I've done is created an array for the values that change, and each time an object of that type is created, the array index is incremented and the next value along is retrieved and put into the constructor (it's generally just X and Y coordinates for most) but if I were to do this for all of the things that change I think i'd end up with a bunch of arrays and it'd get confusing.

This is shown here:

public Actor getActor(String actor)
    {
        String direction = "";
        int i = 0;

        int[] endX = new int[] {13};
        int[] WetTurtleX = new int[] {1,200,400,600,700};
        int[] WetTurtleY = new int[] {376,217};

        if("WetTurtle".equalsIgnoreCase(actor))
        {
            return new WetTurtle(WetTurtleX[i++], 376, -1, 130, 130);
        }
        else if ("End".equalsIgnoreCase(actor))
        {
            return new End(endX[i++],96);
        }
        return null;
    }

And then I created it in my main code like this (I put them into an ArrayList and then add them to the background through that):

objectsToAdd.add(actFact.getActor("End"));
        objectsToAdd.add(actFact.getActor("WetTurtle"));
        for (int i = 0; i < objectsToAdd.size(); i++)
        {
            background.add(objectsToAdd.get(i));
        }

Does anyone have any recommendations/tips on how to handle objects with different parameters within a factory? As even though this idea i've got now works, it's not exactly efficient.

Thanks

Aucun commentaire:

Enregistrer un commentaire