回调函数function的test

/**
 * 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
    callback

}

龙哥说懂得用回调是中级程序员与高级程序员的区别之一。

猜你喜欢

转载自my.oschina.net/u/3744350/blog/1622747