在重构 Java 项目以使用组合而不使用继承时,我仍然存在一个问题,即执行集合的多态排序。
继承示例:
public class AClass
{
private List<OneClassOfManyThatRequireSortedInstances> unsortedList;
public List<OneClassOfManyThatRequireSortedInstances> getSortedList()
{
List<OneClassOfManyThatRequireSortedInstances> sortedList = new ArrayList(this.unsortedList);
Collections.sort(sortedList, SuperClassOfManyThatRequireSortedInstances.orderComparator);
return sortedList;
}
}
现在,在重构之后;类OneClassOfManyThatRequireSortedInstances
不再从 abstract 继承,SuperClassOfManyThatRequireSortedInstances
而是Collections.sort()
期望相互比较的实例。
重构它的最佳方法是什么?
编辑:
为了完整性;我添加了 Comparator 实现并进一步澄清了问题。
public class SuperClassOfManyThatRequireSortedInstances
{
private int order;
public static final Comparator<SuperClassOfManyThatRequireSortedInstances> orderComparator = new Comparator<SuperClassOfManyThatRequireSortedInstances>()
{
public int compare(SuperClassOfManyThatRequireSortedInstances o1, SuperClassOfManyThatRequireSortedInstances o2)
{
if ((o1 == null) && (o2 == null))
{
return 0;
}
if (o1 == null)
{
return -1;
}
if (o2 == null)
{
return 1;
}
return (new Integer(o1.getOrder()).compareTo(new Integer(o2
.getOrder())));
}
};
public int getOrder()
{
return this.order;
}
public void setOrder(int order)
{
this.order = order;
}
}
问题的症结在于重构为组合后,OneClassOfManyThatRequireSortedInstances
不再"is a"
SuperClassOfManyThatRequireSortedInstances
等代码被破坏。
许多类,如OneClassOfManyThatRequireSortedInstances
不再有一个共同的父母。因此,Collections.sort()
不能在这些类中使用Comparator
. 像OneClassOfManyThatRequireSortedInstances
now 这样的类反而有一个SuperClassOfManyThatRequireSortedInstances
成员;一种"has a"
关系。