enes enes - 4 days ago 6
Java Question

How to pass a parameter to a class between different modules' same classes in java?

I have 5 modules and all modules includes same classes, but all classes' content have different codes in to the run method.

mainpackage
| \ moduleA
| \ LoginClass
| + run(hashMapContext)
| \ LogOutClass
| + run(hashMapContext)
| \ GetInfoClass
| + run(hashMapContext)
|
| \ moduleB
| \ LoginClass
| + run(hashMapContext)
| \ LogOutClass
| + run(hashMapContext)
| \ GetInfoClass
| + run(hashMapContext)


I have a field
(moduleType)
and i am trying to this

moduleType = moduleA

getInfo.run(hashMapContext)


How to develop this code?
enter image description here

here is answer thanks to @Jhon D.

public static void main(String[] args) {

ICommon obj = newInstance("a");
obj.run("expect A");

}


public static ICommon newInstance(String type) {

switch (type) {
case "a":
return new ModuleALogin();
case "b":
return new ModuleBLogin();
default:
return null;
}

}

Answer

Use common interface that contains method: run(hashMapContext).

Ok, if you want example. It could be similar to:

public void foo() {
    // ...
    CommonInterface obj = newInstance(module);
    obj.run(hashMapContext);
    // ...
}

public CommonInterface newInstance(module) {
    switch (module) {
        case A:
            return ClassFromModuleA;
        case B:
            return ClassFromModuleB;
        // ...
    }
}
Comments