Factory Design Pattern
Factory Design Pattern
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