100% found this document useful (7 votes)
85K views1 page

Factory Design Pattern

You use the Factory design pattern when you want to define the class of an object at runtime. It also allows you to encapsulate object creation so that you can keep all object creation code in one place.

Uploaded by

Derek Banas
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (7 votes)
85K views1 page

Factory Design Pattern

You use the Factory design pattern when you want to define the class of an object at runtime. It also allows you to encapsulate object creation so that you can keep all object creation code in one place.

Uploaded by

Derek Banas
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 1

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

You might also like