added strategy pattern sample

This commit is contained in:
Ilkka Seppala 2014-08-23 13:18:53 +03:00
parent 2d0905a5e9
commit 6157f22ea4
8 changed files with 96 additions and 0 deletions

View File

@ -38,6 +38,7 @@
<module>memento</module>
<module>observer</module>
<module>state</module>
<module>strategy</module>
</modules>
<build>

23
strategy/pom.xml Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.iluwatar</groupId>
<artifactId>strategy</artifactId>
<version>1.0-SNAPSHOT</version>
<name>strategy</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,17 @@
package com.iluwatar;
public class App
{
public static void main( String[] args )
{
System.out.println("Green dragon spotted ahead!");
DragonSlayer dragonSlayer = new DragonSlayer(new MeleeStrategy());
dragonSlayer.goToBattle();
System.out.println("Red dragon emerges.");
dragonSlayer.changeStrategy(new ProjectileStrategy());
dragonSlayer.goToBattle();
System.out.println("Black dragon lands before you.");
dragonSlayer.changeStrategy(new SpellStrategy());
dragonSlayer.goToBattle();
}
}

View File

@ -0,0 +1,18 @@
package com.iluwatar;
public class DragonSlayer {
private DragonSlayingStrategy strategy;
public DragonSlayer(DragonSlayingStrategy strategy) {
this.strategy = strategy;
}
public void changeStrategy(DragonSlayingStrategy strategy) {
this.strategy = strategy;
}
public void goToBattle() {
strategy.execute();
}
}

View File

@ -0,0 +1,7 @@
package com.iluwatar;
public interface DragonSlayingStrategy {
void execute();
}

View File

@ -0,0 +1,10 @@
package com.iluwatar;
public class MeleeStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
System.out.println("With your Excalibur you severe the dragon's head!");
}
}

View File

@ -0,0 +1,10 @@
package com.iluwatar;
public class ProjectileStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
System.out.println("You shoot the dragon with the magical crossbow and it falls dead on the ground!");
}
}

View File

@ -0,0 +1,10 @@
package com.iluwatar;
public class SpellStrategy implements DragonSlayingStrategy {
@Override
public void execute() {
System.out.println("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!");
}
}