Java 一个简单的回调模式

我们需要定义一个接口:

package linving.test;

public interface MyTestInterface {
    public int getUpdate(int i);

}

接下来给这个接口的实现更新

package linving.test.update;

import linving.test.MyTestInterface;

public class Update {
 public void UpdateSometing(MyTestInterface callback){
     int i = 0;
     while(true){
         i++;
         callback.getUpdate(i);
     }
    
 }
}

主函数:

package linving.test.main;

import linving.test.MyTestInterface;
import linving.test.update.Update;

public class TestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        MyTestInterface callback = new MyTestInterface() {

            @Override
            public int getUpdate(int i) {
                // TODO Auto-generated method stub
                System.out.println(i);
                return i;
            }
        };
        Update u = new Update();
        u.UpdateSometing(callback);
        
        
    }

}

评论

暂无评论