.
interface Measurable {
// Compute the distance from a turret.
// It would be better if you use a superclass of Turret to make your method more general
double distance(Turret p);
};
class Enemy extends Measurable, Combatable {
};
class Turret {
...
Position pos() { return pos; }
boolean isInRange(Combatable c) { ... }
void hit(Combatable combatable) { ... }
};
DistFromTurretComparator implements Comparable<Enemy> {
DistFromTurretComparator(Turret turret) {
this.turret = turret;
}
private int compareTo(Enemy other) {
int dist = distance(turret);
int oDist = other.distance(turret);
return dist > oDist ? + 1 : (dist < oDist ? -1 : 0);
}
private final Turret turret;
};
// Main
Tower tower = new Toweer();
List<Combatable> enemies = new ArrayList<>(Arrays.asList(enemy1, enemy2, ...));
Collections.sort(enemies, new DistFromTurretComparator(tower));
Enemy nearestEnemy = enemies.get(0);
if (tower.hasInRange(enemy)) {
tower.hit(enemy);
}