不過在一些物件導向的程式語言(例如Java)中,我們沒辦法直接把函式傳遞給另一個函式
註:在物件導向的程式語言中,函式(function)被稱做方法(method),之後我會使用方法一詞
在Java中萬物都是物件(唔,其實還有primitive type這東西的存在,不過我們先忽略它),方法沒有辦法單獨宣告與使用,它必須依附在某個類別下。
所以一個通用的解法是用一個interface將方法包起來
- //Comparator.java
- public interface Comparator{
- int compare(int first, int second);
- }
此時我們的bubbleSort可以將Comparator物件傳遞進來,並且在需要時呼叫Comparator的compare方法(第10行)
- //Sorter.java
- public class Sorter{
- public static void main(String []args){
- ...
- }
- public void bubbleSort(int[] array, Comparator c){
- for(int round=0; round<array.length; round++){
- for(int i=0; i<array.length-1; i++){
- if( c.compare(array[i],array[i+1]) > 0){
- int temp = array[i];
- array[i] = array[i+1];
- array[i+1] = temp;
- }
- }
- }
- }
- }
同樣當我們需要不同排序邏輯時,只需要實做Comparator介面就好
- //SortByAsc.java
- public class SortByAsc implements Comparator{
- public int compare(int first, int second){
- if(first < second){
- return -1;
- }
- else if(first > second){
- return 1;
- }
- else{
- return 0;
- }
- }
- }
使用時只要new一個有實做Comparator介面的物件即可。
- //Sorter.java
- public class Sorter{
- public static void main(String []args){
- int[] array = {5,2,8,1};
- Sorter obj = new Sorter();
- obj.bubbleSort(array, new SortByAsc());
- for(int elem : array){
- System.out.println(elem);
- }
- }
- public void bubbleSort(int[] array, Comparator c){
- ...
- }
- }
這裡的SortByAsc就是所謂的function object,它僅僅是方法(函式)的物件而已。
沒有留言:
張貼留言