Make a UFO
UFO Rocket Boss UFO EnemyShipFactory.java <Factory>
public EnemyShip makeEnemyShip(String newShipType) { EnemyShip newShip = null; if (newShipType.equals("U")){ return new UFOEnemyShip(); } else if (newShipType.equals("R")){ return new RocketEnemyShip(); } else if (newShipType.equals("B")){ return new BigUFOEnemyShip(); } else return null; }
name speed damage EnemyShip.java <AbstractClass>
public abstract class EnemyShip { private String name; private double speed; private double damage; public String getName() { return name; } public void setName(String newName) { name = newName; } public double getDamage() { return amtDamage; } public void setDamage(double newDamage) { amtDamage = newDamage; }
EnemyShipTesting.java <Store>
public static void main(String[] args){ // Create the factory object EnemyShipFactory shipFactory = new EnemyShipFactory(); // Enemy ship object EnemyShip theEnemy = null; Scanner userInput = new Scanner(System.in); System.out.print("What type of ship? (U / R / B)"); if (userInput.hasNextLine()){ String typeOfShip = userInput.nextLine(); theEnemy = shipFactory.makeEnemyShip(typeOfShip); if(theEnemy != null){ doStuffEnemy(theEnemy); } else System.out.print("Please enter U, R, or B next time"); }
BigUFOEnemyShip
public class BigUFOEnemyShip extends EnemyShip { public BigUFOEnemyShip(){ setName("Big UFO Enemy Ship"); setDamage(40.0); setSpeed(10.0); } }
UFOEnemyShip
public class UFOEnemyShip extends EnemyShip { public UFOEnemyShip(){ setName("UFO Enemy Ship"); setDamage(20.0); setDamage(20.0);
The Factory Pattern allows you to create objects without specifying the exact class of object that will be created.
<client>
<factory> EnemyShipFactory
<abstract> EnemyShip
Implements
UFOEnemyShip BigUFOEnemyShip
Factory Design Pattern