Java Reference
In-Depth Information
macro . record (() -> editor . save ());
macro . record (() -> editor . close ());
macro . run ();
In fact, we can do this even better by recognizing that each of these lambda expressions is
performing a single method call. So, we can actually use method references in order to wire
the editor's commands to the macro object (see Example 8-8 ).
Example 8-8. Using method references to build up a macro
Macro macro = new
new Macro ();
macro . record ( editor: : open );
macro . record ( editor: : save );
macro . record ( editor: : close );
macro . run ();
The command pattern is really just a poor man's lambda expression to begin with. By using
actual lambda expressions or method references, we can clean up the code, reducing the
amount of boilerplate required and making the intent of the code more obvious.
Macros are just one example of how we can use the command pattern. It's frequently used in
implementing component-based GUI systems, undo functions, thread pools, transactions,
and wizards.
NOTE
There is already a functional interface with the same structure as our interface Action in
core Java— Runnable . We could have chosen to use that in our macro class, but in this
case it seemed more appropriate to consider an Action to be part of the vocabulary of our
domain and create our own interface.
Strategy Pattern
The strategy pattern is a way of changing the algorithmic behavior of software based upon a
runtime decision. How you implement the strategy pattern depends upon your circumstances,
but in all cases the main idea is to be able to define a common problem that is solved by dif-
ferent algorithms and then encapsulate all the algorithms behind the same programming in-
terface.
Search WWH ::




Custom Search