mardi 2 août 2016

private static list which contains all object constructed

I'm writing animation program, in which many balls are running around and bouncing.

I made Ball class which represents ball's behaviour.

When I implement ball's collisioin with another ball,
I have to check the all other balls.
So I made this class.

public class Ball{

    private static final List<Ball> allBalls;
    static{
        allBalls = new ArrayList<>();
    }

    private Ball(){}

    public static Ball getNewBall(){
        Ball ball = new Ball();
        allBalls.add(ball);
        return ball;
    }

    public void collision(){
        for(Ball b : allBalls){
            //check whether b is colliding with me
            //and if colliding, change speed of me and b.
        }
    }

}

Is this kind of design (to hold all objects in private static list) good or bad ?

Aucun commentaire:

Enregistrer un commentaire