abstract method use vs regular methods

前端 未结 6 1079
醉酒成梦
醉酒成梦 2021-01-13 06:45

I would like to know the difference between two conventions:

  1. Creating an abstract base class with an abstract method which will be implemented later on the der
6条回答
  •  无人共我
    2021-01-13 06:56

    The idea of putting abstract methods in a base class and then implementing them in subclasses is that you can then use the parent type instead of any specific subclass. For example say you want to sort an array. You can define the base class to be something like

    abstract class Sorter {
        public abstract Array sort(Array arr);
    }
    

    Then you can implement various algorithms such as quicksort, mergesort, heapsort in subclasses.

    class QuickSorter {
        public Array sort(Array arr) { ... }
    }
    
    class MergeSorter {
        public Array sort(Array arr) { ... }
    }
    

    You create a sorting object by choosing an algorithm,

    Sorter sorter = QuickSorter();
    

    Now you can pass sorter around, without exposing the fact that under the hood it's a quicksort. To sort an array you say

    Array sortedArray = sorter.sort(someArray);
    

    In this way the details of the implementation (which algorithm you use) are decoupled from the interface to the object (the fact that it sorts an array).

    One concrete advantage is that if at some point you want a different sorting algorithm then you can change QuickSort() to say MergeSort in this single line, without having to change it anywhere else. If you don't include a sort() method in the parent, you have to downcast to QuickSorter whenever calling sort(), and then changing the algorithm will be more difficult.

提交回复
热议问题