Search code examples
javaarchitecturesubclassing

How to choose and use subclass of an object (MemoryType) based on subclass of another object (FractalType) outside of it's skope


I'm doing some factal calculations, and for different kinds of fractal TypeX I need to remember different calculation data MemX, and call on these data different procedures.

For example for TypeA, remembers and uses values from previous calculation. TypeB remembers only iteration, TypeC none of those. But each TypeX remembers some common data.

For example MemA has .conjugation(), MemB has somethinElse()

TypeA extends Type
TypeB extends Type
MemA extends Mem
MemB extends Mem

So when I call method math() which does the calculation, I need to pass different memory object MemX. I don't want to pack everything into one Mem, as I need to do these calculations for many points for each pixel.

Basically I want to make one of the calls below, depending on which class is in variable type.

type.math(MemA m)
type.math(MemB m)

I use it like this

bigCalculationMethodWhichNeedsToBeSuperFast() {
    // initiate mem common data
    type.math(mem);
    // use mem common data
}

type is either TypeA or TypeB, and mem is either MemA or MemB respectively

scope of mem is the bigCalculationMethodWhichNeedsToBeSuperFast() which is called by many threads at the same time. One mem for each thread. So I want to create minimum of new objects or call minimum of expensive operations.

I initiate type like this.

public static Type type = new TypeX

Based on this declaration, I want my architecture to choose correct object for Mem

So the question is, how to solve this in Java? I was thinking how to use Interfaces or Generics, but I don't get how in this case.

It is mainly about how to define and use abstract method Type.math(...)

Or maybe it shouldn't be defined as abstract method in abstract class. Or maybe it would be better to structure these objects in another way?


Solution

  • Solved this by adding one more layer of abstraction between TypeX and Type.

    And made specific MemX methods in new TypeAbstracX classes.

    No Generics, No interfaces. Problem solved.