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.
Advertisement
Answer
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 } //.... }