繁体   English   中英

带有不同getter setter的未知子类型的一般配置

[英]Generic configuration of unknown subtypes with differing getters setters

我希望能够读写一堆相关但不同的类的某些字段, 而又不知道它们具体是什么类型的具体类 我所知道的是,它们具有一些我希望能够普遍访问和修改的参数类型。 而且由于我不知道该类是什么具体类型,所以我也不知道每个类的具体参数类型是什么。

  • 我认为以下方法可行,但是否足够好/可能有什么问题?
  • 还是针对此问题有更好的方法/甚至建立的设计模式?

允许通用可配置性的超类

public abstract class ParametrizerBase<P1, P2> {
    public P1 Param1;
    public P2 Param2;
}

需要一些具有特定参数的具体类

public class SomeConcreteClass extends ParametrizerBase<Boolean, String> {
    public SomeConcreteClass(Boolean enabled, String task){
        Param1 = enabled;
        Param2 = task;
    }
    // ... does something with the parameter data
}

另一类具有不同数据类型的具体类

public class AnotherConcreteClass extends ParametrizerBase<Integer, Date> {
    public AnotherConcreteClass(Integer numberOfItems, Date when){
        Param1 = numberOfItems;
        Param2 = when;
    }
    // ... does something with the data it holds
}

用法示例

    ArrayList<ParametrizerBase> list;

    public void initSomewhere() {
        SomeConcreteClass some = new SomeConcreteClass(true,"Smth");
        AnotherConcreteClass another = new AnotherConcreteClass(5, new Date());
        list = new ArrayList<ParametrizerBase>();
        list.add(some);
        list.add(another);
    }

    public void provideDataElsewhere() {
        for (ParametrizerBase concrete : list) {
            String param1Type = concrete.Param1.getClass().getName();
            if (param1Type.contains("Boolean")) {
                 Boolean value = concrete.Param1;
                 // Now could let user modify this Boolean with a checkbox 
                 // and if they do modify, then write it to concrete.Param1 = ...
                 // All without knowing what Param1 is (generic configuration)
            } else if (param1Type.contains("Integer")) {
                 Integer value = concrete.Param1;
                 // ...
            } // ...
            // Same for Param2 ...
        }
    }

使用Java接口描述获取器和设置器。 让所有具体的类都实现此接口。 将对象强制转换为接口类型,然后根据需要调用getter和setter。

暂无
暂无

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

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