首页 > 解决方案 > 如何为相同的功能处理两个不同的对象

问题描述

我有以下对象之一,ObjOneObjTwo,进入我的函数,它们都共享相似的 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

编辑:我导入了这些对象,所以我不能为它们声明父类,它们确实共享对我的场景很方便的 getter/setter。

标签: javaoopobjectcasting

解决方案


一种更 OO 的方法是在您可以控制的新对象中组合您不控制的对象。然后根据您控制的对象编写您的 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"));
}

推荐阅读