2017-12-08 8 views
0

void sort()メソッドを共通にしてソートクラス(挿入、マージなど)を作成したい場合は、これらのクラスが実装または拡張できるインターフェイスまたは抽象クラスが必要ですから。Java design strucutre

しかし、ソートメソッドを静的に使用する予定で、静的メソッドを抽象スーパークラスに保つことはできません。

このような実装にはどのような適切な方法がありますか?

+2

それは静的にしないでください! – ajb

+4

あなたは2つの矛盾した欲望を持っています。静的および多態性。それはどちらか一方です。 –

+1

OK、もっと真剣に:ソーターオブジェクトが必要です。このオブジェクトはソートする配列ではなく、ソートアルゴリズムを提供することを目的としたオブジェクトです。ソートメソッドは、そのオブジェクトのインスタンスメソッドになります。 – ajb

答えて

0

staticメソッドsort(int data [ ])を使用する解決方法は、Stategyパターン(intデータを使用して簡素化)を使用して行うことができます。
enter image description here あなたが言ったように、例えば、グループのすべてのあなたのソート戦略を、InsertionSortMergeSortQuicksort等...インターフェースSortAlgorithmに抽象メソッドを実装しsort(int data [])
はその後、私の例ではchoiceは、クライアント

class Client{ 
    public static void main(String [ ] args){ 
     Scanner sc = new Scanner(System.in); 
     int choice = sc.nextInt(); 
     int data= new int [5] 
     data={3,7,7,1,0}; 
     Sorter.sort(data,choice); 
    } 
0

によって与えられた整数final sort(int data [ ], int choice)を使用する抽象型SortAlgorithmへの参照を所有しているクラスSorterを書くまあ、私はあなたがそれを複雑にしようとしていると思います。あなたの問題はまっすぐです。いくつかのソート関数をコーディングするだけです。あなたはどこでもオブジェクト指向の思考を適用しようとすることはできません。これは、さまざまな再利用可能なアルゴリズムの実装に過ぎません。あなたが本当にこれを設計する必要がある場合。あなたはこのように試すことができます:

interface Sorter<T> { 

    // This method accepts any type of object and sorts it and return it in sorted order 
    //Used Generics to support all types. You can read T as List or Array if you want to understand it in a simple way 
    public T sort(T t); 
} 



class MergeSort implements Sorter<int[]> { 


    @Override 
    public int[] sort(int[] numbersToSort) { 
    //algorithm goes here 

    } 

} 


class BubbleSort implements Sorter<int[]> { 

    @Override 
    public int[] sort(int[] numbersToSort) { 
     //algorithm goes here 
    } 

} 


class InsertionSort implements Sorter<int[]> { 

    @Override 
    public int[] sort(int[] numbersToSort) { 
     //algorithm goes here 
    } 

} 





enum SortingAlgorithms{ 
INSERTIONSORT, 
BUBBLESORT, 
MERGESORT; 

} 

class SorterFactory { 
    public static Sorter<int[]> getSortingAlgorithm(SortingAlgorithms alg) { 
     switch(alg) { 
     case INSERTIONSORT : 
      return new InsertionSort(); 

     case BUBBLESORT : 
      return new BubbleSort(); 

     case MERGESORT : 
      return new MergeSort(); 

     default: 
      return new BubbleSort(); 
     } 
    } 
} 



public class SortingExecutor { 
    public static void main (String... cmdArgs) { 

     int[] toBeSorted = {6, 7, 1, 0, 3}; 

     //get a bubble sort algorith which can take int[] as input and return the sorted int[] as output 
     Sorter<int[]> bubbleSort = SorterFactory.getSortingAlgorithm(SortingAlgorithms.BUBBLESORT); 
     bubbleSort.sort(toBeSorted); 



    } 
} 
0

ここでブリッジデザインのパターンが役立ちます。 1つの階層には、集計クラスのソーター参照でデータを保持する異なる集計が含まれています。 ソーターを基本クラスとする別の階層では、具象クラスでさまざまな種類のソートアルゴリズムが提供されます。

利点は両方の側面が独立して成長することができます。

唯一の橋パターンから変化が集約・ソーターの関係が双方向になることになります(イテレータに類似リトルビット)