I want to have multiple isolated instances of a "commander" class (no static fields or methods) which brings together all the classes below it. The classes below should be ignorant of this "commander" class's existence in order to abstract implementation details.

In this first attempt, LowerClass1 has to access the CentralClass in order to interact with LowerClass2 (through an instance of LowerClass2). CentralClass should only be able to access the classes below itself, the classes below CentralClass should not be able to access it. This example shows LowerClass1 accessing the class above it (CentralClass) in order to reach another class on it's own level (LowerClass2).

public class CentralClass {
    public LowerClass1 lowerClass1;
    public LowerClass2 lowerClass2;
}

public class LowerClass1 {
    public void exampleMethod1() {
        CentralClass.lowerClass2.exampleMethod2();
    }
}

public class LowerClass2 {
    public void exampleMethod2() {
    
    }
}

Basically, LowerClass1 is being made aware of the existence of the "commander" class above it in order to access the instance of the LowerClass2 class on its own level.

In this next attempt, while LowerClass1 can access LowerClass2 without accessing CentralClass, CentralClass can no longer have isolated instances because of the static methods of LowerClass2. While the upwards flow of the class hierarchy is preserved, I can no longer create multiple isolated instances of CentralClass.

public class CentralClass {
    public LowerClass1 lowerClass1;
}

public class LowerClass1 {
    public void exampleMethod1() {
        LowerClass2.exampleMethod2();
    }
}

public class LowerClass2 {
    public static void exampleMethod2() {
    
    }
}

In both cases, either the flow was broken where a class ascended and descended multiple class levels (breaking hierarchy and introducing confusion), or the higher class level was unable to isolate multiple instances because of the static connections between lower classes.

How would I preserve the hidden abstraction of the lower classes to the upper classes while avoiding the use of static so the upper classes can have multiple isolated instances? Would using separate class loaders be an option? Are there any design patterns that might be helpful in this situation?

1

There are 1 best solutions below

0
On

I found a solution that isolates the classes while preserving their hierarchy.

public class CentralClass {
    public LowerClass1 lowerClass1 = new LowerClass1(new LowerClass2());
}

public class LowerClass1 {
    private LowerClass2 lowerClass2;
    
    public LowerClass1(LowerClass2 lowerClass2) {
        this.lowerClass2 = lowerClass2;
    }
    
    public void exampleMethod1() {
        this.lowerClass2.exampleMethod2();
    }
}

public class LowerClass2 {
    public void exampleMethod2() {
    
    }
}