簡體   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