简体   繁体   English

Java和正确使用类层次结构

[英]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. 在某些时候,很多xxxModule被制作并存储在AbstractModule列表中。 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. 这样,您可以直接调用module.doModuleStuff()而不是进行切换,这不是很好,因为我仍然需要为此将其强制转换回其子类。

Problem is, is If put this code in each child class, how do I call the right method when my list contains AbstractModules? 问题是,如果将这段代码放在每个子类中,当列表包含AbstractModules时如何调用正确的方法? And I mean without having this typeEnum and switch case. 我的意思是没有这个typeEnum和switch的情况。

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. 您还可以检查可以完成工作的设计模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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