回调函数的接口文件:
package cxl.learn.callback; //通过接口来实现委托回调函数 public interface CustomDelegatesImpl<T> { void runCallback(T objOfSomeType); }
一些测试代码:
package cxl.learn.callback; public class SomeFunc { public void Run(CustomDelegatesImpl<SomeType> callback){ //运行公共业务 System.out.println("一段公共的业务逻辑————开始"); //....业务上下文中的对象 SomeType obj = new SomeType(); obj.name = "业务对象1"; obj.id = 1; //.............. //在此处通知回调函数 callback.runCallback(obj); System.out.println("一段公共的业务逻辑————结束"); } }
package cxl.learn.callback; public class SomeFunc2 { public void Run(CustomDelegatesImpl<SomeType2> callback){ //运行公共业务 System.out.println("一段公共的业务逻辑————开始"); //....业务上下文中的对象 SomeType2 obj = new SomeType2(); obj.assetName = "业务对象2"; obj.x = 0;obj.y=100;obj.z = 300; obj.width = 1.999f; obj.height = 2.9999f; //.............. //在此处通知回调函数 callback.runCallback(obj); System.out.println("一段公共的业务逻辑————结束"); } }
package cxl.learn.callback; public class SomeType { public String name; public int id; }
package cxl.learn.callback; public class SomeType2 { public String assetName; public int x,y,z; public float width, height; @Override public String toString() { return "SomeType2{" + "assetName='" + assetName + '\'' + ", x=" + x + ", y=" + y + ", z=" + z + ", width=" + width + ", height=" + height + '}'; } }
import cxl.learn.callback.CustomDelegatesImpl; import cxl.learn.callback.SomeType; public class TestCallback implements CustomDelegatesImpl<SomeType> { @Override public void runCallback(SomeType objOfSomeType) { System.out.println("回调函数2==》" + objOfSomeType.id); } }
main函数:
import cxl.learn.callback.*; public class main { public static void main(String[] args){ System.out.println("callback learn !!"); //lambda CustomDelegatesImpl<SomeType> listeners0 = new CustomDelegatesImpl<SomeType>() { @Override public void runCallback(SomeType objOfSomeType) { System.out.println("回调函数1==》"+objOfSomeType.name); } }; TestCallback listeners1 = new TestCallback(); SomeFunc func = new SomeFunc(); func.Run(listeners0); func.Run(listeners1); CustomDelegatesImpl<SomeType2> listeners2 = new CustomDelegatesImpl<SomeType2>() { @Override public void runCallback(SomeType2 objOfSomeType) { System.out.println("回调函数3==》"+objOfSomeType.toString()); } }; SomeFunc2 func2 = new SomeFunc2(); func2.Run(listeners2); } }
运行结果:
callback learn !!
一段公共的业务逻辑————开始
回调函数1==》业务对象1
一段公共的业务逻辑————结束
一段公共的业务逻辑————开始
回调函数2==》1
一段公共的业务逻辑————结束
一段公共的业务逻辑————开始
回调函数3==》SomeType2{assetName='业务对象2', x=0, y=100, z=300, width=1.999, height=2.9999}
一段公共的业务逻辑————结束
暂无关于此日志的评论。