mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-10-14 00:16:48 +00:00
* #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:
1 parent
25ed2540f4
commit
18a1a725ee
5 files changed
+103
-2
No files matched your search
@@ -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