Skip to content

Instantly share code, notes, and snippets.

@ttowncompiled
Created October 9, 2018 02:46
Show Gist options
  • Save ttowncompiled/35862a02fed084f66a643de685df7eea to your computer and use it in GitHub Desktop.
Save ttowncompiled/35862a02fed084f66a643de685df7eea to your computer and use it in GitHub Desktop.
A basic example of a design issue that can be solved with the Strategy pattern.
import java.util.Random;
public abstract class Character {
private int health;
public Character(int health) {
this.health = health;
}
public boolean wound(int dmg) {
this.health = (this.health > dmg) ? this.health-dmg : 0;
return this.health == 0;
}
public int meleeAttack() {
Random rnd = new Random();
return rnd.nextInt(6)+rnd.nextInt(6)+rnd.nextInt(6)+3;
}
public int rangedAttack() {
Random rnd = new Random();
return rnd.next(4)+rnd.next(4)+2;
}
}
public class Knight extends Character {
public Knight() {
super(18);
}
}
public class Rogue extends Character {
public Rogue() {
super(12);
}
}
public class GiantRat extends Character {
public GiantRat() {
super(10);
}
@Override
public int meleeAttack() {
Random rnd = new Random();
return rnd.nextInt(4)+rnd.nextInt(4)+2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment