I was just trying out few java-8 functional programming , I had few doubts on the behaviour of the lamda expressions. I have tried to explain the problem below with simple Command Pattern.
public interface Editor {
public void open();
public void close();
// public void save();
}
Editor Implementation
public class MyEditor implements Editor {
@Override
public void open() {
System.out.println("...opening");
}
@Override
public void close() {
System.out.println("...closing");
}
}
Interface Action
// this is actually a @FunctionalInterface
public interface Action {
public void perform();
}
Actionable items.
public class Open implements Action {
private final Editor editor;
public Open(Editor editor) {
this.editor = editor;
}
@Override
public void perform() {
editor.open();
}
// Similarly Close implements Action...
...
A Macro to run all the actions.
public class Macro {
private final List<Action> actions;
public Macro() {
actions = new ArrayList<>();
}
public void record(Action action) {
actions.add(action);
}
public void run() {
actions.forEach(Action::perform);
}
}
Now running the Macro is where the interesing part is .
public class RunMacro {
public static void main(String[] args) {
Editor editor= new MyEditor();
Macro macro = new Macro();
macro.record(() -> editor.open());// Line 4
macro.record(new Close(editor)); // Line 5
macro.run();
}
}
My question is , during the execution of Line 4, How does Java understand that to create a instanceof Open and add it into macro. In short lamdba expressions is behaving same way as Line 5. This whole pattern becomes a lot simpler with lambda expressions BUT does the functional programming with OOPS makes the development at very abstract level or less verbose?
Courtesy of problem : O'Reilly Media : Java 8 Lamdbas
Could any one please clarify this.?