使用组合而不是继承时 Comparator<T> 的替代方法是什么?

SPB*_*SPB 1 java sorting collections inheritance composition

在重构 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,经过重构;类OneClassOfManyThatRequireSortedInstances不再从抽象继承,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;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题的关键在于,重构为组合后,OneClassOfManyThatRequireSortedInstances不再"is a" SuperClassOfManyThatRequireSortedInstances等代码被破坏。

许多类OneClassOfManyThatRequireSortedInstances不再有一个共同的父类。因此,Collections.sort()不能在这些类中仅使用Comparator. 像OneClassOfManyThatRequireSortedInstances现在这样的类有一个SuperClassOfManyThatRequireSortedInstances成员;一种"has a"关系。

Alp*_*per 5

假设有两个类,CarTrain。你可以创建一个像

public interface SpeedProvider {
    int getSpeed();
}
Run Code Online (Sandbox Code Playgroud)

然后,两个CarTrain实现SpeedProvider接口

public class Car implements SpeedProvider {
    int maxSpeed = 220;

    @Override
    public int getSpeed() {
        return maxSpeed;
    }
}

public class Train implements SpeedProvider {
    int maxSpeed = 300;

    @Override
    public int getSpeed() {
        return maxSpeed;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,你可以实现一个Comparator比较两个SpeedProvider

public class VehicleComparator implements Comparator<SpeedProvider> {
    @Override
    public int compare(SpeedProvider o1, SpeedProvider o2) {
        /* ... */
        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)