Java Reference
In-Depth Information
iif ( name . contains ( "Apollo" )) {
System . out . println ( "We made it!" );
}
}
}
In a similar vein to the previous patterns, in our traditional example our client code specific-
ally wires up a layer of boilerplate classes that don't need to exist if we use lambda expres-
sions (see Examples 8-19 and 8-20 ).
Example 8-19. Client code building up a Moon using classes and things landing on it
Moon moon = new
new Moon ();
moon . startSpying ( new
new Nasa ());
moon . startSpying ( new
new Aliens ());
moon . land ( "An asteroid" );
moon . land ( "Apollo 11" );
Example 8-20. Client code building up a Moon using lambdas and things landing on it
Moon moon = new
new Moon ();
moon . startSpying ( name -> {
iif ( name . contains ( "Apollo" ))
System . out . println ( "We made it!" );
});
moon . startSpying ( name -> {
iif ( name . contains ( "Apollo" ))
System . out . println ( "They're distracted, lets invade earth!" );
});
moon . land ( "An asteroid" );
moon . land ( "Apollo 11" );
One thing to think about with both the observer and the strategy patterns is that whether to
go down the lambda design route or the class route depends a lot on the complexity of the
strategy or observer code that needs to be implemented. In the cases I've presented here, the
code is simple in nature, just a method call or two, and fits the new language features well. In
some situations, though, the observer can be a complex class in and of itself, and in those
situations trying to squeeze a lot of code into one method can lead to poor readability.
Search WWH ::




Custom Search