Rafał Krawczyk
Rafał Krawczyk

Reputation: 23

How to avoid circular references in Java class planning?

I have a simple class structure where a Map aggregates Cells, and each Cell contains an Actor. However, to make it work, I've had to tightly couple them and create circular references. This has caused numerous issues during serialization. My question is: should I focus on improving the internal structure of this system, or would it be better to dedicate my efforts to learning more about serialization?

Here is the basic structure:

public class Map {
    private Cell[][] cells;
    private List<Actor> actors; // dependency injection
    public void moveActors() {
        // logic uses Actor.move()
    }
}
public class Cell {
    private Actor actor;
    private Map map; // dependency injection
    public Cell getNeighbourCell(){
        // logic uses map
        return cell;
    }
}
public class Actor {
    private Cell cell; // dependency injection
    public void move() {
        // logic uses cell getNeighbourCell()
    }
}

Upvotes: 1

Views: 36

Answers (0)

Related Questions