A pattern that relies on inheritance in which a method creates objects returning common parent class.
Contents
Example of Uses
- Parsing by different file types (txt, doc, wpd, rtf, etc.)
- Modes of a game
Intent
- reduce code duplication for complex processes upon object creation
Implementation
Template method
public class Game { public Game() { this.createMonster(Math.floor(10.0 * this.getHpRatio())); } protected float getHpRatio() { return 50; } }
public class HardMode extends Game { @Override protected float getHpRatio() { return 1.25; } }
public class EasyMode extends Game { @Override protected float getHpRatio() { return 0.5; } }
Interfaces
public interface Product { public String getName(); }
public interface ProductFactory { public Product makeProduct(); }
public class Shoe implements Product { @Override public String getName() { return "Nerky Flying Jadens"; } }
public class ShoeFactory implements ProductFactory { @Override public Product makeProduct() { return new Show(); } }
public class Test { public static void main(String[] args) { ProductFactory factory = new ShoeFactory(); Product shoe = factory.makeProduct(); System.out.println(shoe.getName()); } }