Last active
October 9, 2018 02:59
-
-
Save ttowncompiled/361fecb282a3ae71427e70451170c6a3 to your computer and use it in GitHub Desktop.
A basic example of the Strategy pattern.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
public interface MeleeAttackBehavior { | |
public int meleeAttack(); | |
} | |
public interface RangedAttackBehavior { | |
public int rangedAttack(); | |
} | |
public class Melee3d6 implements MeleeAttackBehavior { | |
public int meleeAttack() { | |
Random rnd = new Random(); | |
return rnd.nextInt(6)+rnd.nextInt(6)+rnd.nextInt(6)+3; | |
} | |
} | |
public class Melee2d4 implements MeleeAttackBehavior { | |
public int meleeAttack() { | |
Random rnd = new Random(); | |
return rnd.nextInt(4)+rnd.nextInt(4)+2; | |
} | |
} | |
public class Ranged2d4 implements RangedAttackBehavior { | |
public int rangedAttack() { | |
Random rnd = new Random(); | |
return rnd.nextInt(4)+rnd.nextInt(4)+2; | |
} | |
} | |
public class NoRangedAttack implements RangedAttackBehavior { | |
public int rangedAttack() { | |
return 0; | |
} | |
} | |
public abstract class Character { | |
private int health; | |
private MeleeAttackBehavior melee; | |
private RangedAttackBehavior ranged; | |
public Character(int health, MeleeAttackBehavior melee, RangedAttackBehavior ranged) { | |
this.health = health; | |
this.melee = melee; | |
this.ranged = ranged; | |
} | |
public int wound(int dmg) { | |
this.health = (this.health > dmg) ? this.health-dmg : 0; | |
return this.health == 0; | |
} | |
public int meleeAttack() { | |
return this.melee.meleeAttack(); | |
} | |
public int rangedAttack() { | |
return this.ranged.rangedAttack(); | |
} | |
} | |
public class Knight extends Character { | |
public Knight() { | |
super(18, new Melee3d4(), new NoRangedAttack()); | |
} | |
} | |
public class Rogue extends Character { | |
public Rogue() { | |
super(12, new Melee3d6(), new Ranged2d4()); | |
} | |
} | |
public class GiantRat extends Character { | |
public GiantRat() { | |
super(10, new Melee2d4(), new NoRangedAttack()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment