摘要:
Java接口提供了一個很好的方法來實現回調函數
作者
在MS
Java的接口提供了一種很好的機制來讓我們達到和回調相同的效果
舉個例子來說
public interface InterestingEvent
{
// This is just a regular method so it can return something or
// take arguments if you like
public void 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
if (somethingHappened)
{
// Signal the even by invoking the interface
ie
}
//
}
//
}
在這個例子中
希望收到事件通知的代碼必須實現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
}
//
}
希望這點小技巧能給你帶來方便
關於作者
John D
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25825.html