55 * The Strategy pattern (also known as the policy pattern) is a software design pattern that enables
66 * an algorithm's behavior to be selected at runtime.
77 * <p>
8+ * Before Java 8 the Strategies needed to be separate classes forcing the developer
9+ * to write lots of boilerplate code. With modern Java it is easy to pass behavior
10+ * with method references and lambdas making the code shorter and more readable.
11+ * <p>
812 * In this example ({@link DragonSlayingStrategy}) encapsulates an algorithm. The containing object
913 * ({@link DragonSlayer}) can alter its behavior by changing its strategy.
1014 *
@@ -17,6 +21,7 @@ public class App {
1721 * @param args command line args
1822 */
1923 public static void main (String [] args ) {
24+ // GoF Strategy pattern
2025 System .out .println ("Green dragon spotted ahead!" );
2126 DragonSlayer dragonSlayer = new DragonSlayer (new MeleeStrategy ());
2227 dragonSlayer .goToBattle ();
@@ -26,5 +31,19 @@ public static void main(String[] args) {
2631 System .out .println ("Black dragon lands before you." );
2732 dragonSlayer .changeStrategy (new SpellStrategy ());
2833 dragonSlayer .goToBattle ();
34+
35+ // Java 8 Strategy pattern
36+ System .out .println ("Green dragon spotted ahead!" );
37+ dragonSlayer = new DragonSlayer (
38+ () -> System .out .println ("With your Excalibur you severe the dragon's head!" ));
39+ dragonSlayer .goToBattle ();
40+ System .out .println ("Red dragon emerges." );
41+ dragonSlayer .changeStrategy (() -> System .out .println (
42+ "You shoot the dragon with the magical crossbow and it falls dead on the ground!" ));
43+ dragonSlayer .goToBattle ();
44+ System .out .println ("Black dragon lands before you." );
45+ dragonSlayer .changeStrategy (() -> System .out .println (
46+ "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!" ));
47+ dragonSlayer .goToBattle ();
2948 }
3049}
0 commit comments