構成を使用し、継承を使用しないように 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"
関係。