* #1469 Add Strategy Pattern lambda implementation After Java 8. Also take advantage of enum * #1469 Update class diagrams * #1469 Update README.md Add lambda programmatic example * #1469 Remove unused imports Co-authored-by: Subhrodip Mohanta <subhrodipmohanta@gmail.com>
This commit is contained in:
@ -122,6 +122,51 @@ Program output:
|
||||
You cast the spell of disintegration and the dragon vaporizes in a pile of dust!
|
||||
```
|
||||
|
||||
What's more, the new feature Lambda Expressions in Java 8 provides another approach for the implementation:
|
||||
|
||||
```java
|
||||
public class LambdaStrategy {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(LambdaStrategy.class);
|
||||
|
||||
public enum Strategy implements DragonSlayingStrategy {
|
||||
MeleeStrategy(() -> LOGGER.info(
|
||||
"With your Excalibur you severe the dragon's head!")),
|
||||
ProjectileStrategy(() -> LOGGER.info(
|
||||
"You shoot the dragon with the magical crossbow and it falls dead on the ground!")),
|
||||
SpellStrategy(() -> LOGGER.info(
|
||||
"You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"));
|
||||
|
||||
private final DragonSlayingStrategy dragonSlayingStrategy;
|
||||
|
||||
Strategy(DragonSlayingStrategy dragonSlayingStrategy) {
|
||||
this.dragonSlayingStrategy = dragonSlayingStrategy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
dragonSlayingStrategy.execute();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And here's the dragonslayer in action.
|
||||
|
||||
```java
|
||||
LOGGER.info("Green dragon spotted ahead!");
|
||||
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy);
|
||||
dragonSlayer.goToBattle();
|
||||
LOGGER.info("Red dragon emerges.");
|
||||
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy);
|
||||
dragonSlayer.goToBattle();
|
||||
LOGGER.info("Black dragon lands before you.");
|
||||
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy);
|
||||
dragonSlayer.goToBattle();
|
||||
```
|
||||
|
||||
Program output is the same as above one.
|
||||
|
||||
## Class diagram
|
||||
|
||||

|
||||
|
Reference in New Issue
Block a user