Collection method(Collection c) {
// select some elements from c based on some filter
// and return a new collection
}
现在,在这种情况下,
Collection
是一些抽象类(例如 C# 中的 IList
或 Java 中的 List
),有多个实现。我一直在想,到底什么是生成抽象集合的正确过程?在方法内部创建具体集合并返回它,这样做可以吗?例如:
Collection method(Collection c) {
Collection cc = new ConcreteCollection();
// select some elements from c based on some filter
return cc;
}
当然,这会对结果集产生限制,并且如果出现某些原因需要将方法的结果转换为与方法内部使用的不同具体集合,则会产生问题。
或者,使用反射来确定c的实际具体类型并创建该类的实例:
Collection method(Collection c) {
Collection cc = c.getClass().newInstance();
// select some elements from c based on some filter
return cc;
}
由于某些原因,这对我来说并不是非常“优雅”。我非常感谢您在此事上提供一些见解。