public class ShipPool implements Iterable<Ship> {
public final Fleet fleet;
- public final ShipPool ancestor;
+ private ShipPool parent;
private HashSet<Ship> allocatedShips = new HashSet<Ship>();
public ShipPool(Fleet fleet) { this(fleet, null); }
- public ShipPool(ShipPool ancestor) { this(ancestor.fleet, ancestor); }
- public ShipPool(Fleet fleet, ShipPool ancestor) {
+ public ShipPool(ShipPool parent) { this(parent.fleet, parent); }
+ public ShipPool(Fleet fleet, ShipPool parent) {
this.fleet = fleet;
- this.ancestor = ancestor;
+ this.parent = parent;
}
public Iterator<Ship> iterator() { return allocatedShips.iterator(); }
public void allocateShip(Ship ship) {
if (allocatedShips.contains(ship))
throw new RuntimeException("already allocated!");
+ if (parent != null)
+ parent.allocateShip(ship);
allocatedShips.add(ship);
}
/** allocate a ship */
public Ship allocateShip(String type) {
Ship ship = null;
- if (ancestor != null) {
- ship = ancestor.allocateShip(type);
+ if (parent != null) {
+ ship = parent.allocateShip(type);
} else {
for(int i=0; ; i++) {
ship = fleet.getShip(type, i);
if (!allocatedShips.contains(ship))
throw new RuntimeException("ship " + ship + " released but was not allocated");
allocatedShips.remove(ship);
- if (ancestor != null) ancestor.releaseShip(ship);
+ if (parent != null) parent.releaseShip(ship);
}
public void releaseAll() {
for (Ship ship : toRelease)
releaseShip(ship);
}
+
+ public void setParent(ShipPool parent) {
+ if (this.parent!=null) {
+ for (Ship ship : allocatedShips)
+ this.parent.releaseShip(ship);
+ this.parent = null;
+ }
+ if (parent != null) {
+ for (Ship ship : allocatedShips)
+ parent.allocateShip(ship);
+ }
+ this.parent = parent;
+ }
+
+ public void assertAllocated(Ship ship) {
+ if (allocatedShips.contains(ship)) return;
+ if (parent==null) throw new RuntimeException("assertAllocated() failed");
+ parent.assertAllocated(ship);
+ }
+
}