java中回调的实现

参考: 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();
    }

}

//回调的价值在于它的灵活性--在运行时决定调用哪个方法。
posted @ 2008-05-18 20:46  shine_panda  阅读(236)  评论(0编辑  收藏  举报