dinsdag 21 juni 2016

Alternative implementation of an Interface with lambda

Introduction

Normally to have an implementation of an Interface is extra work 
  1. Create a class
  2. Implement the Interface
  3. Implementing the  method(s)
I always thought of this as the boring part except implementing the method(s)
 So I was fooling a bit around with Lambda's in Java and figured a way of interface implementation without creating an extra class for it. I thought that this way might be nice when the implementation of the Interface happens  only ones. Like in Spring when you use Inversion of Control.
Lets have a look at how it could be done with Lambda's

The solution to the problem 

First of all you create the Interface:

public interface WorkerInterface {
  //The method to implement 
  void doSomeWork();
}


Secondary the class that is having the interface and the implemented method:

public class LambdaTest {
    //The method that executes the Interfaces method.
    private void execute(WorkerInterface worker) {
        worker.doSomeWork();
    }

    //Just the plain old main to start up this class.
    public static void main(String [] args) {
        LambdaTest lambdaTest = new LambdaTest();
        lambdaTest.run();
    }

    private void run() {
        //A list with names to start this examples
        List<String> names = new ArrayList<>();
        names.add("Test1");
        names.add("Test2");
        names.add("Test3");
        //The lambda way to do a for loop
        //With the first arrow you assign name to the execute method.
         names.forEach(name ->
        //With the second arrow you assign the execute method.
        // to the implementation you had in mind.
        execute( () ->
       System.out.println(name) ));
    }
}

Conclusion
As you can see this works quite easy. By using a double assignment one assign the data to the execute method and the other to assign the execute method to the implementation, it is possible to make an Interface method execute something without an extra class file.
Have fun!

Geen opmerkingen:

Een reactie posten