Home > front end >  Avoiding circular depenency between Arena and Portal
Avoiding circular depenency between Arena and Portal

Time:12-06

I'm trying to resolve this ciruclar dependency while preferebly keeping both objects immutable.

public class Arena {

    private final Portal portal;

    Arena(Portal portal) {
        this.portal = portal;
    }

    void close() {
        portal.close();
    }

    void start() {

    }
}

public class Portal {

    private final Arena arena;

    Portal(Arena arena) {
        this.arena = arena;
    }

    void close() {

    }

    void start() {
        arena.start();
    }

}

Basically, I need portal to be able to activate itself, and start the arena. Opposite, I need Arena to reset & close itself, and the portal. I found a solution by having two HashMap's <Arena, Portal> and <Portal, Arena>, however I want to figure out if it's a better way to solve this for learning and progression.

The classes are made more simple in here, as in reality they have more variables and identifiers.

CodePudding user response:

Why not a wrapper class for both Arena and Portal:

public class PortalArena {

    private final Portal portal;

    private final Arena arena;

    PortalArena(Portal portal, Arena arena) {
        this.portal = portal;
        this.arena = arena;
    }
    
    void startPortal() {
        portal.start();
        arena.start();
        // Rest of the logic here
    }

    void closeArena() {
        arena.close();
        portal.close();
        // Rest of the logic here
    }
 
    //....

}

CodePudding user response:

you can use dependency inversion, so Portal will not depend on Arena

interface Startable{
  void start();
}

class Arena extends Startable{...}

and then:

class Portal{
  private final Startable arena;
  ...
}

though looking at Arena and Portal methods, it looks like those are not immutable

  • Related