/** * Created by zengxc on 2018/2/22. * 回調函數在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(); /** * 執行方法 */ 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){ // 關閉 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
callbackjava
}程序員
龍哥說懂得用回調是中級程序員與高級程序員的區別之一。redis