Sunday, May 22, 2016

Template method and Builder pattern using lambdas

Today I want to show you how easy is to implement a Template method pattern using lambdas and Consumer functional interface in Java 8. To illustrate our example, we are going to develop a software to send commands to a robot.

 Before the command is sent, it is required to establish the connection with the robot and set the robot to status ready (ready to receive commands). Finally after the command execution the robot must be set to idle status. Then each command execution requires 4 steps listed below.

  1. Establish connection with the robot.
  2. Set the robot to ready status.
  3. Execute the command.
  4. Set the robot to idle status.
Take a look how to implement this, with Java 8 using lambdas.

As you can see in the above code, the client is not worried about how to obtain a robot connection, it only sends the command it want to execute on the robot. At the same time, we are using the lambda to provide a fluent interface to configure the command (Builder pattern).

The method 'executes' acts as template method, and you can see how the RobotCommand object is instantiated locally. Then using the method 'accept', the created RobotCommand is passed to the lambda context.

You can find the complete code here

No comments:

Post a Comment