Java Reference
In-Depth Information
Compressor zipCompressor = new
new Compressor ( new
new ZipCompressionStrategy ());
zipCompressor . compress ( inFile , outFile );
As with the command pattern discussed earlier, using either lambda expressions or method
references allows us to remove a whole layer of boilerplate code from this pattern. In this
case, we can remove each of the concrete strategy implementations and refer to a method
that implements the algorithm. Here the algorithms are represented by the constructors of the
relevant OutputStream implementation. We can totally dispense with the GzipCompres-
sionStrategy and ZipCompressionStrategy classes when taking this approach.
Example 8-14 is what the code would look like if we used method references.
Example 8-14. Instantiating the Compressor using method references
Compressor gzipCompressor = new
new Compressor ( GZIPOutputStream: : new
new );
gzipCompressor . compress ( inFile , outFile );
Compressor zipCompressor = new
new Compressor ( ZipOutputStream: : new
new );
zipCompressor . compress ( inFile , outFile );
Observer Pattern
The observer pattern is another behavioral pattern that can be improved and simplified
through the use of lambda expressions. In the observer pattern, an object, called the subject ,
maintains a list of other objects, which are its observers . When the state of the subject
changes, its observers are notified. It is heavily used in MVC-based GUI toolkits in order to
allow view components to be updated when state changes in the model without coupling the
two classes together.
Seeing GUI components update is a bit boring, so the subject that we'll be observing is the
moon! Both NASA and some aliens want to keep track of things landing on the moon.
NASA wants to make sure its Apollo astronauts have landed safely; the aliens want to invade
Earth when NASA is distracted.
Let's start by defining the API of our observers, which I'll give the name LandingObserver .
This has a single observeLanding method, which will be called when something lands on
the moon ( Example 8-15 ) .
Example 8-15. An interface for observing organizations that land on the moon
public interface
interface LandingObserver
LandingObserver {
public void
void observeLanding ( String name );
Search WWH ::

Custom Search