函数式接口

主要介绍:编程式接口作为方法参数,这种使用方式比较适合使用批处理操作。

1、无参无返回值

public interface MyInterOne {
    void fun();
}
public interface DemoOneInterface {

    // zhelikeijiangqitiquchulai
    static void print(MyInterOne myInterOne) {
        Objects.requireNonNull(myInterOne);
        myInterOne.fun();
        System.out.println("shangmiandezhixignwanle,wolaizuoyihuier");
    }
}
public class DemoOne implements DemoOneInterface {

    public static void main(String[] args) {
        DemoOneInterface.print(()->{
            System.out.println("hello,world");
        });
    }
}

其实这里print参数中做的事情就是函数式接口中方法该来做的事情。因为传递的是接口,所以我们可以直接传递进去fun方法的实现,其他的步骤,已经来给我们做好了。函数式接口作为方法参数,这种使用方式很多。

2、无参有返回值

public interface MyInterface3 {
    String fun();
}
public interface DemoTwoInterface {
    static String print(MyInterface3 myInterface3){
        Objects.requireNonNull(myInterface3);
        return myInterface3.fun();
    }
}
public class DemoTwo {
    public static void main(String[] args) {
        final String print = DemoTwoInterface.print(() -> "hello,world");
        System.out.println("---------");
        System.out.println(print);
    }
}

3、有参无返回值

public interface MyInterface4 {
    void fun(int i);
}
public interface DemoThreeInterface {
    static void print(MyInterface4 myInterface4){
        Objects.requireNonNull(myInterface4);
        myInterface4.fun(6666);
    }
}
public class DemoThree {
    public static void main(String[] args) {
        // youcanwufanhuizhi,laiduizhelidezhijinxignchuli
        DemoThreeInterface.print(i -> {
            System.out.println("value is : "+i);
        });
    }
}

4、有参有返回值

public interface MyInterface4 {
    String print(int i);
}
public interface DemoFourInterface {
    static String print(MyInterface4 myInterface4){
        return myInterface4.print(666);
    }
}
public class DemoFour {
    public static void main(String[] args) {
        final String print = DemoFourInterface.print(i -> {
            final String s = String.valueOf(i)+123456;
            return s;
        });
        System.out.println("=============");
        System.out.println(print);
    }
}

5、实际案例参考

5.1、mybatis中的批量处理:

首先定义接口操作:

@FunctionalInterface
public interface BatchOperateService {
    void operate(SqlSession sqlSession);
}

再次定义接口:

public interface BatchService {
    boolean batchOperate(BatchOperateService batchOperateService);
}

定义实际操作工作类:

@Component
@AllArgsConstructor
public class BatchServiceImpl implements BatchService{

    private static final Logger logger = LoggerFactory.getLogger(BatchServiceImpl.class);

    private final SqlSessionFactory sqlSessionFactory;

    /**
     * 批处理操作!其他的事情已经做好了,下面只需要再次来做其他的事情即可,极其类似模板方法的使用方式
     * @param batchOperateService 实际要进行操作的函数式接口
     * @return
     */
    @Override
    public boolean batchOperate(BatchOperateService batchOperateService) {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,Boolean.FALSE);
        try {
            batchOperateService.operate(sqlSession);
            sqlSession.commit();
        }catch (Exception e){
            logger.error("批处理操作出现的问题是:"+e);
            sqlSession.rollback();
            return false;
        }finally {
            sqlSession.close();
        }
        return true;
    }
}

5.2、编程式事务

private class SqlSessionInterceptor implements InvocationHandler {
        private SqlSessionInterceptor() {
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            SqlSession sqlSession = SqlSessionUtils.getSqlSession(SqlSessionTemplate.this.sqlSessionFactory, SqlSessionTemplate.this.executorType, SqlSessionTemplate.this.exceptionTranslator);

            Object unwrapped;
            try {
                Object result = method.invoke(sqlSession, args);
                if (!SqlSessionUtils.isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
                    sqlSession.commit(true);
                }

                unwrapped = result;
            } catch (Throwable var11) {
                unwrapped = ExceptionUtil.unwrapThrowable(var11);
                if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
                    SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
                    sqlSession = null;
                    Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException)unwrapped);
                    if (translated != null) {
                        unwrapped = translated;
                    }
                }

                throw (Throwable)unwrapped;
            } finally {
                if (sqlSession != null) {
                    SqlSessionUtils.closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
                }

            }

            return unwrapped;
        }
    }
posted @ 2022-01-19 01:37  雩娄的木子  阅读(53)  评论(0编辑  收藏  举报