JAVA通过接口来实现CALLBACK

在网上看了好多关于java回调的文章,自己总结了一下(个人意见,仅供参考):

JAVA通过接口来实现CALLBACK。  
  例:  
  1.class   A,class   B  
  2.class   A实现接口operate  
  3.class   B拥有一个参数为operate接口类型的函数test(operate   o)  
  4.class   A运行时调用class   B中test函数,以自身传入参数  
  5.class   B已取得A,就可以随时回调A所实现的operate接口中的方法

=========================================================================

接口和回调.编程一个常用的模式是回调模式,在这种模式中你可以指定当一个特定时间发生时回调对象上的方法。

==========================================================================

概括一句:回调函数实际上就是在调用某个函数(通常是API函数)时,将自己的一个函数(这个函数为回调函数)的地址作为参数传递给那个函数。而那个函数在需要的时候,利用传递的地址调用回调函数,这时你可以利用这个机会在回调函数中处理消息或完成一定的操作。

===========================================================================

借用John D. Mitchell的例子应该比较好理解


在MS-Windows或者X-Window系统的事件驱动模型中,当某些事件发生的时候,开发人员已经熟悉通过传递函数指针来调用处理方法。而在Java的面向对象的模型中,不能支持这种方法,因而看起来好像排除了使用这种比较舒服的机制,但事实并非如此。

Java的接口提供了一种很好的机制来让我们达到和回调相同的效果。这个诀窍就在于定一个简单的接口,在接口之中定义一个我们希望调用的方法。

举个例子来说,假设当一个事件发生的时候,我们想它被通知,那么我们定义一个接口:

public   interface  InterestingEvent
{

    
// This is just a regular method so it can return something or

    
// take arguments if you like.

    
public void interestingEvent ();

}

这就给我们一个控制实现了该接口的所有类的对象的控制点。因此,我们不需要关心任何和自己相关的其它外界的类型信息。这种方法比C函数更好,因为在C++风格的代码中,需要指定一个数据域来保存对象指针,而Java中这种实现并不需要。

发出事件的类需要对象实现InterestingEvent接口,然后调用接口中的interestingEvent ()方法。

public   class  EventNotifier
{

    
private InterestingEvent ie;

    
private boolean somethingHappened; 

    
public EventNotifier (InterestingEvent event)
    
{

        
// Save the event object for later use.

        ie 
= event; 

        
// Nothing to report yet.

        somethingHappened 
= false;

    }
 

    
//  

    
public void doWork ()
    
{

        
// Check the predicate, which is set elsewhere.

        
if (somethingHappened)
        
{

            
// Signal the even by invoking the interface's method.

            ie.interestingEvent ();

        }


        
//
    }
 

    
// 

}

在这个例子中,我们使用了somethingHappened这个标志来跟踪是否事件应该被激发。在许多事例中,被调用的方法能够激发interestingEvent()方法才是正确的。

希望收到事件通知的代码必须实现InterestingEvent接口,并且正确的传递自身的引用到事件通知器。

public   class  CallMe  implements  InterestingEvent
{

    
private EventNotifier en; 

    
public CallMe ()
    
{

        
// Create the event notifier and pass ourself to it.

        en 
= new EventNotifier (this);

    }
 

    
// Define the actual handler for the event.

    
public void interestingEvent ()
    
{

        
// Wow!  Something really interesting must have occurred!

        
// Do something

    }
 

    
//

}


你可能感兴趣的:(java)