简体   繁体   中英

Java and correct use of class hierarchy

TypeEnum
    MATERIAL,
    OPERATION,
    SIGNATURE;

class AbstractModule
    TypeEnum typeEnum
    String name
    String color

class MaterialModule extends AbstractModule
    some properties unique to this module

class OperationModule extends AbstractModule
    some properties unique to this module

class SignatureModule extends AbstractModule
    someProperties unique to this module

at some point a lot of xxxModule are made and stored in a AbstractModule list. Then later all that list is being iterated and a switch case is use to cast back the abstract module to its child class and do stuff

switch (module.getTypeEnum) {
            case MATERIAL:
                MaterialModule materialModule = (MaterialModule) module;
                //do stuff with materialModule unique property
                break;
            case OPERATION:
                OperationModule operationModule = (OperationModule) module;
                //do stuff with operationModule unique property
                break;
            case SIGNATURE:
                SignatureModule signatureModule = (SignatureModule) module;
                //do stuff with signature module unique property
                break;

each "do stuff with module unique property" should be in a method in each child class

that way you can just call module.doModuleStuff() instead of doing a switch, well no because I still need to cast it back to its child class for that.

Problem is, is If put this code in each child class, how do I call the right method when my list contains AbstractModules? And I mean without having this typeEnum and switch case.

Thanks.

You can create a method that is public that will call private method with the unique properties you want. For example :

public abstract class AbsModule{
    public void abstract doSomething();
}

public class Module1 implements AbsModule{
    public void doSomething(){
        doSomethingForModule1();
    }
    private void doSomethingForModule1(){
        Your code here
    }
}

public class Module2 implements AbsModule{
    public void doSomething(){
        doSomethingForModule2();
    }
    private void doSomethingForModule2(){
        Your code here
    }
}

You can also check design pattern that can do the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM