[New Features of Java8] 02 Functional Interface and Lambda Expression Practical Exercise: Surrounding Execution Mode to Parameterize Behavior

Java8 was released by Oracle in 2014 and is the most revolutionary version after Java5.  

Java 8 absorbs the essence of other languages ​​and brings a series of new features such as functional programming, lambda expressions, and streams. After learning these new features, you can achieve efficient coding and elegant coding.

01 Introduction of examples

First introduce a practical example, we often write a dao class to manipulate the database, such as query records, insert records, etc.

The query and insert functions are implemented in the following code (the introduction of Mybatis tripartite parts):

public class StudentDao {

    /**
     * 根据学生id查询记录
     * @param id 学生id
     * @return 返回学生对象
     */
    public Student queryOne(int id) {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession session = null;
        try {
            session = sqlSessionFactory.openSession();
            // 根据id查询指定的student对象
            return session.selectOne("com.coderspace.mapper.student.queryOne", id);
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    /**
     * 插入一条学生记录
     * @param student 待插入对象
     * @return true if success, else return false
     */
    public boolean insert(Student student) {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession session = null;
        try {
            session = sqlSessionFactory.openSession();
            // 向数据库插入student对象
            int rows = session.insert("com.coderspace.mapper.student.insert", student);
            return rows > 0;
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
  }

Observing the above two methods can be found:

return session.selectOne("com.coderspace.mapper.student.queryOne", id);

int rows = session.insert("com.coderspace.mapper.student.insert", student);
Except for the above two lines, the other codes are the same. First obtain the session, then perform the core operation, and finally close the session .

 

The code of getting session and closing session revolves around specific core operation code, we can call this code as template code.

If there is another requirement and the method of deleting student needs to be implemented, then you will definitely copy the code for obtaining session and closing session above. There are too many duplicate codes in this way. As a good engineer, you will definitely not tolerate this kind of thing. occur.

 

02 Surround execution mode to parameterize behavior

How to solve it? Now please take out our protagonist: surround execution mode to parameterize behavior.

What is behavior parameterization? In the above example, we have observed that except for the core operation code, the other codes are exactly the same, so can we pass the core operation code as an input parameter to the template method and execute them according to different behaviors.

Variable objects are easily passed in as parameters, and behaviors can be passed in using lambda expressions.

The following refactoring of the previous example can be divided into three steps:

(1) Define functional interface;

(2) Define template method;

(3) Pass the lambda expression

The above three-step formula can be applied to all surround execution modes.

Step 1: Define a functional interface

@FunctionalInterface
public interface DbOperation<R> {
    /**
     * 通用操作数据库接口
     * @param session 数据库连接session
     * @param mapperId 关联mapper文件id操作
     * @param params 操作参数
     * @return 返回值,R泛型
     */
    R operate(SqlSession session, String mapperId, Object params);
}

Defines an abstract method of operate, receives three parameters, and returns the generic R.

Step 2: Define the template method

DbOperation is a functional interface, passed as an input parameter:

public class CommonDao<R> {
    
    public R proccess(DbOperation<R> dbOperation, String mappperId, Object params) {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession session = null;
        try {
            session = sqlSessionFactory.openSession();
            // 核心操作
            return dbOperation.operate(session, mappperId, params);
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }
  }

Step 3: Pass the lambda expression

// 根据id查询学生
String mapperId = "com.coderspace.mapper.student.queryOne";
int studentNo = 123;

CommonDao<Student> commonDao = new CommonDao<>();
// 使用lambda传递具体的行为
Student studentObj = commonDao.proccess(
        (session, mappperId, params) -> session.selectOne(mappperId, params),
        mapperId, studentNo);

// 插入学生记录
String mapperId2 = "com.coderspace.mapper.student.insert";
Student student = new Student("coderspace", 1, 100);

CommonDao<Boolean> commonDao2 = new CommonDao<>();
// 使用lambda传递具体的行为
Boolean successInsert = commonDao2.proccess(
        (session, mappperId, params) -> session.selectOne(mappperId, params),
        mapperId2, student);

The above three steps have been implemented. If you want to implement the delete method, there is no need to change a line of code in CommonDao, just pass in different parameters to the caller.

The surround execution mode is very useful in the real environment. If you find a bunch of fixed codes surrounded by a few lines of changeable code, you should consider using the lambda surround execution mode at this time.

--- end ---

Laughter architects are not too bad in technology. Scan the QR code or search for "Laughing Architects" on WeChat and follow the official account, and more technical dry goods will be posted as soon as possible!

Finally, I will give you a bonus. The laughable architect has collected a lot of genuine e-books on related technologies. After paying attention to the official account, reply to the number 888 to get it for free.

Guess you like

Origin blog.csdn.net/guoguo527/article/details/108805410