簡體   English   中英

如何為同一個 Function 處理兩個不同的對象

[英]How to Handle two different Objects for same Function

我有以下對象之一, ObjOneObjTwo,進入我的 function,它們都共享相似的 getter/setter。

目前我有一個中介,一個映射器,用於跨內部方法,但可能有一種更簡潔的方法可以在沒有映射器但缺乏特定語法的情況下執行此操作。

public String mapper(Object obj){

   Map<String, String> map = new HashMap<>();
   
   if(obj instanceof ObjOne){
      ObjOne obj1 = (ObjOne)obj;
      map.put("firstKey", obj1.getFirstValue());
   }
   else if(obj instanceof ObjTwo){
      ObjTwo obj2 = (ObjTwo)obj
      map.put("firstKey", obj1.getFirstValue());
   }

   return secondFunction(map);
      
}

private String secondFunction(Map<String, String> map){
   
   return thirdFunction(map.get("firstKey"));
}

(ObjOne || ObjTwo)obj).getFirstValue()是否有這樣的語法來輸入這里的thirdFunction

編輯:我導入了這些對象,所以我不能為它們聲明父 class,它們共享對我的場景很方便的 getter/setter。

一種更面向對象的方法是在您可以控制的新 object 中組合您無法控制的對象。 然后根據您控制的 object 編寫您的 API。

final class ObjOne {
    String getFirstValue() {
        return "foo";
    }
}

final class ObjTwo {
    String getFirstValue() {
        return "bar";
    }
}

class MyAdapter {
    final Map<String, String> map = new HashMap<>();

    MyAdapter(ObjOne o1) {
        this(o1.getFirstValue());
    }

    MyAdapter(ObjTwo o2) {
        this(o2.getFirstValue());
    }

    MyAdapter(String firstKey) {
        map.put("firstKey", firstKey);
    }
}

public String secondFunction(MyAdapter adapter) {
    return thirdFunction(adapter.map.get("firstKey"));
}

一個建議不要通過 Object 而是做這樣的事情創建一個基本 model 使用這里多態性。 例如。

abstract class BaseObj {

    abstract public String getFirstValue();
}

class ObjOne extends BaseObj{


    @Override
    public String getFirstValue() {
        return  "something useful";
    }
}

class ObjTwo extends BaseObj{


    @Override
    public String getFirstValue() {
        return  "something useful";
    }
}

不確定這里的用例是什么,但你總是可以相應地塑造。

public String mapper(BaseObj obj){
    Map<String, String> map = new HashMap<>();
    map.put("firstKey", obj.getFirstValue()); //common function call
    return secondFunction(map);

}

private String secondFunction(Map<String, String> map){

    return thirdFunction(map.get("firstKey"));
}

private String thirdFunction(String firstKey) {
    return null;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM