/** * Created by zengxc on 2018/2/22. * Application of callback function in java */ public interface Function<E, T> { public T callback(E e); }
/** * Created by zengxc on 2018/2/22. */ public class FunctionMethod { public void init(){ System.out.println("start init"); } public String run(String key, String value){ System.out.println("runtime program"); return key + value; } public void close(){ System.out.println("end close"); } }
/** * Created by zengxc on 2018/2/22. */ public class RedisUtils implements RedisUtilsImpl{ private FunctionMethod functionMethod = new FunctionMethod(); /** * Execute method */ public <T> T execute(Function<FunctionMethod, T> function){ FunctionMethod functionMethod = null; this.functionMethod.init(); try { functionMethod = getNewClass(); return function.callback(functionMethod); } catch (Exception e) { e.printStackTrace (); } finally { if (null != functionMethod){ // closure functionMethod.close(); } } return null; } public FunctionMethod getNewClass(){ return functionMethod; } @Override public String set(final String key,final String value) { return this.execute(new Function<FunctionMethod, String>() { @Override public String callback(FunctionMethod functionMethod) { return functionMethod.run(key, value); } }); }
@Test public void testFunction() { RedisUtils redisUtils = new RedisUtils (); String set = redisUtils.set("call", "back"); System.out.println(set); }
console{
start init
runtime program
end close
callback
}
Brother Long said that knowing how to use callbacks is one of the differences between intermediate programmers and advanced programmers.