Java Reference
In-Depth Information
Example 8-5. A macro consists of a sequence of actions that can be invoked in turn
public
public class
class
Macro
Macro
{
private
private final
final
List
<
Action
>
actions
;
public
public
Macro
() {
actions
=
new
new
ArrayList
<>();
}
public
public
void
void
record
(
Action action
) {
actions
.
add
(
action
);
}
public
public
void
void
run
() {
actions
.
forEach
(
Action:
:
perform
);
}
}
When we come to build up a macro programmatically, we add an instance of each command
that has been recorded to the
Macro
object. We can then just run the macro and it will call
each of the commands in turn. As a lazy programmer, I love the ability to define common
workflows as macros. Did I say “lazy”? I meant focused on improving my productivity. The
Macro
object is our client code and is shown in
Example 8-6
.
Example 8-6. Building up a macro with the command pattern
Macro macro
=
new
new
Macro
();
macro
.
record
(
new
new
Open
(
editor
));
macro
.
record
(
new
new
Save
(
editor
));
macro
.
record
(
new
new
Close
(
editor
));
macro
.
run
();
How do lambda expressions help? Actually, all our command classes, such as
Save
and
Open
, are really just lambda expressions wanting to get out of their shells. They are blocks of
behavior that we're creating classes in order to pass around. This whole pattern becomes a
lot simpler with lambda expressions because we can entirely dispense with these classes.
lambda expressions instead.
Example 8-7. Using lambda expressions to build up a macro
Macro macro
=
new
new
Macro
();
macro
.
record
(() ->
editor
.
open
());