我有一个Table类,它实现了某种类型对象的ForwardingMultimap。我想知道是否过度创建一个从对象中提取密钥的接口,这样调用者在调用“值”时处理“Entry”对象就不会烦人了。或者让调用者自己放置对象和密钥会更好吗?如果这没关系,创建一个单独的类来处理每个键如下更好,还是调用者自己实现它?
public class CustomObject {
public String propertyOne;
public int propertyTwo;
}
public interface ITableAggKey {
Object getKey(CustomObject customObj);
}
public class Table extends ForwardingMultimap<Object, CustomObject> {
Multimap m_map;
public Table(ITableAggKey aggKey){
m_map = HashMultimap.create();
m_aggKey = aggKey;
}
public boolean put(CustomObject obj) {
m_map.put(m_aggKey.getKey(obj), obj);
}
}
public class CustomObjectAggKeys {
public static final aggKeyOne = new ITableAggKey(){
@Overide
public Object getKey(CustomObject obj){
return obj.propertyOne;
}
};
public static final aggKeyOne = new ITableAggKey(){
@Overide
public Object getKey(CustomObject obj){
return obj.propertyTwo;
}
};
}
答案 0 :(得分:2)
var searchParams = ['342421111', '77HE2', 'U7IA2'];
async.map(searchParams, function(param, next) {
Product.find({ UPC: param }).exec(function(err, results) {
if (err) return next(err);
if (results.length) return next(null, results);
vendorProduct.find({ SKU: param }).exec(function(err, results) {
if (err) return next(err);
if (results.length) return next(null, results);
next(null, 'No results');
});
});
}, function(err, searchResults) {
if (err) {
// handle the error
return;
}
console.log(searchResults);
});
如果你不能使用Java8。添加功能界面。
public class Table<K, T> extends ForwardingMultimap<K, T> {
Multimap<K, T> m_map;
Function<T, K> m_aggKey;
public Table(Function<T, K> aggKey){
m_map = HashMultimap.create();
m_aggKey = aggKey;
}
public boolean put(T obj) {
m_map.put(m_aggKey.apply(obj), obj);
}
}
public static void main(String[] args) {
Table<String, CustomObject> IndexOne = new Table<>(x -> x.propertyOne);
Table<Integer, CustomObject> IndexTwo = new Table<>(x -> x.propertyTwo);
}
并且
public interface Function<T, K> {
K apply(T arg);
}