java - 如何为相同的功能处理两个不同的对象
问题描述
我有以下对象之一,ObjOne
并ObjTwo,
进入我的函数,它们都共享相似的 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。
解决方案
一种更 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"));
}
推荐阅读
- python - Statsmodels OLS 公式中的数据帧计数
- installation - v8 没有安装日志
- javascript - javascript - toFixed (444.2).toFixed(14) 中的隐蔽问题
- vnc-server - 使用tigervnc通过XDMCP访问centos7.8,键盘事件失效
- azure - 是否可以使用 Terragrunt 和 Terraform 在 Azure 上的 1 个租户中提供 2 个订阅?
- hive - Hive ACID 表抛出错误 FAILED: UnsupportedOperationException openTxn is not supported in aws EMR
- gitlab - gitlab globbing 表达式不匹配
- swift - Swift 错误:无法从“A”转换为“A?” 使用泛型时
- excel - 只要按下多个键,Vba Excel就会在用户窗体中显示一个按钮
- ios - 如何修改 UIDatePicker 中的“shortWeekdaySymbols”?