Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses. Advantage: i)When we don't know ahead of time what class object you need. ii)To Encapsulate object creation. iii)It allows the sub-classes to choose the type of object to create.
public abstract class EnemyShip import { java.util.Scanner; private String name; public class EnemyShipTesting { private double amtDamage; public String getName() { return public static void main(String[] args){ name; } EnemyShipFactory shipFactory = new EnemyShipFactory(); public void setName(String EnemyShip theEnemy = null; newName) { Scanner userInput = new Scanner(System.in); name = newName; } System.out.print("What type of ship? (U / R / B)"); public double getDamage() { if (userInput.hasNextLine()){ return amtDamage; } String typeOfShip = userInput.nextLine(); public void setDamage(double theEnemy = shipFactory.makeEnemyShip(typeOfShip); newDamage){ if(theEnemy != null){ amtDamage = newDamage; } doStuffEnemy(theEnemy); public void followHeroShip(){ } else SOP(getName() + " the hero");} System.out.print("Please enter U, R, or B next time");} public void displayEnemyShip(){ } SOP(getName() + " is on the public static void doStuffEnemy(EnemyShip anEnemyShip) screen");} { public void enemyShipShoots() { anEnemyShip.displayEnemyShip(); SOP(getName() + " attacks " + anEnemyShip.followHeroShip(); UFOEnemyShip getDamage() +:" hero");} anEnemyShip.enemyShipShoots();} package } com.e.demo.factory; } public class UFOEnemyShip extends EnemyShip { public UFOEnemyShip(){ UML Diagam of Factory Pattern setName("UFO Enemy Ship"); setDamage(20.0);} EnemyShipFactory: } package com.e.demo.factory; public class EnemyShipFactory{ public EnemyShip makeEnemyShip(String newShipType){ if (newShipType.equals("U")){ BigUFOEnemyShip: RocketEnemyShip: return new UFOEnemyShip(); package com.e.demo.factory; package com.e.demo.factory; } else if public class BigUFOEnemyShip extends UFOEnemyShip { (newShipType.equals("R")){ public class RocketEnemyShip extends EnemyShip { return new RocketEnemyShip(); public BigUFOEnemyShip(){ public RocketEnemyShip(){ } else if (newShipType.equals("B")){ setName("Big UFO Enemy Ship"); setName("Rocket Enemy Ship"); return new BigUFOEnemyShip(); setDamage(40.0); setDamage(10.0); } else return null; } } } } } }