Java一种接口模板的写法

1、定义一个接口,exectue方法为抽象方法

import java.io.IOException;

public interface CommonOperateCallBack<T> {

    /**
     * 前置检查
     */
    default void before() {

    }
    /**
     * 执行结果.
     *
     * @return object
     */
    T execute() throws IOException;

    /**
     * 后置检查.
     */
    default void after() {

    }
}

2、定义一个操作模板

import java.io.IOException;

public class WebOperateTemplate<T> {

    /**
     * web模板执行.
     *
     * @param operateCallback 操作模板
     * @return
     */
    public static void execute(CommonOperateCallBack operateCallback) {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();


        try {
            // 前置处理
            operateCallback.before();
            // 服务处理
            System.out.println(""+ operateCallback.execute());
            // 后置处理
            operateCallback.after();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            stopWatch.stop();
            long time = stopWatch.getTotalTimeMillis();
            System.out.println("花费时间" + time);

        }


    }

}

3、实际实现



 @Test
    void contextLoads() {
       WebOperateTemplate.execute(new CommonOperateCallBack<User>(){


          //实际功能在此实现,执行顺序按照操作模板定义的
           @Override
           public User execute() throws IOException {
               return new User("执行结束");
           }

           @Override
           public void after() {
               System.out.println("after");
           }


           @Override
           public void before() {
               System.out.println("before--");
           }
       });

    }

before--
User{name='执行结束'}
after
花费时间0
posted @ 2024-04-11 11:12  cgl_dong  阅读(14)  评论(0编辑  收藏  举报