java中回調的實現

來源:互聯網
上載者:User

參考: think in java

//定義一個介面
interface Incrementable...{
    void increment();
}

//一個簡單的介面實作類別
class Callee1 implements Incrementable...{
    private int i = 0;
    public void increment()...{
        i++;
        System.out.println (i);
    }
    
    
}

class MyIncrement...{
    void increment()...{
        System.out.println ("other operator");
    }
    
    static void f(MyIncrement mi)
    ...{
        mi.increment();    
            
    }
}


//Callee2 想改變 MyIncrement中 increment()方法的行為。 
// 主要是因為Callee2有一個完全不同的incr ()方法 
// 要解決的問題是在調用increment 方法的時候 改而調用 incr方法
//父類有一個increment 不能因為字類的用途而覆蓋這個方法 
//所以字類重新寫了一個 incr 方法。

class Callee2 extends MyIncrement...{
    private int i = 0;
    //一個用來替代incrment方法的行為的方法。
    private void incr()...{
        i++;
        System.out.println (i);    
    }
    //內部類實現Incrementable介面
    private class Closure implements Incrementable ...{
        public void increment()...{
            incr();
        }
    }
    
    //獲得一個回調的引用
    Incrementable getCallBackReference()...{
        return new Closure();
    }
    
    
}

class Caller...{
    private Incrementable callbackReferences;
    
    //它只需要一個介面。
    Caller (Incrementable chb)...{
        callbackReferences = chb;
    }
    
    void go()...{
        callbackReferences.increment();
    }
    
    
}

 class Callbacks...{
    public static void main(String[] args)...{
        Callee1 c1 = new Callee1();
        Callee2 c2 = new Callee2();
        
        MyIncrement.f(c2);
        
        
        
        Caller caller1 = new Caller(c1);
        //用戶端完全不知道 caller2 中的incrment方法的實現。
        //事實上Callee2完全改變了incrment方法的行為(調用了另一個方法)
        Caller caller2  = new Caller(c2.getCallBackReference());
        
        caller1.go();
        caller1.go();
        
        caller2.go();
        caller2.go();
    }
}
//回調的價值在於它的靈活性--在運行時決定調用哪個方法。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.