1

構成を使用し、継承を使用しないように 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は抽象から継承されなくなりまし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()を 1 つの実装だけでこれらのクラス間で使用することはできませんComparator。nowなどのクラスOneClassOfManyThatRequireSortedInstancesには代わりにSuperClassOfManyThatRequireSortedInstancesメンバーがあります。"has a"関係。

4

3 に答える 3

1

質問は意味がありません。Comparator<T>コンポジションで使用されます。継承を使用する場合の代替手段はComparable<T>. あなたの質問は前に戻っています。

于 2013-05-20T10:24:35.567 に答える