Author: techfox9
Design Patterns – Factory pattern (Creational) basic example..
Friday, June 20th, 2008 @ 1:51 pm
This pattern allows the application to defer to runtime the decision of which
object from a related set to instantiate .
From http://en.wikipedia.org/wiki/Factory_method_pattern
abstract class Pizza { public abstract double getPrice(); } class HamAndMushroomPizza extends Pizza { public double getPrice() { return 8.5; } } class DeluxePizza extends Pizza { public double getPrice() { return 10.5; } } class HawaiianPizza extends Pizza { public double getPrice() { return 11.5; } } class PizzaFactory { public enum PizzaType { HamMushroom, Deluxe, Hawaiian } public static Pizza createPizza(PizzaType pizzaType) { switch (pizzaType) { case HamMushroom: return new HamAndMushroomPizza(); case Deluxe: return new DeluxePizza(); case Hawaiian: return new HawaiianPizza(); } throw new IllegalArgumentException("The pizza type " + pizzaType + " is not recognized."); } } class PizzaLover { /* * Create all available pizzas and print their prices */ public static void main (String args[]) { for (PizzaFactory.PizzaType pizzaType : PizzaFactory.PizzaType.values()) { System.out.println("Price of " + pizzaType + " is " + PizzaFactory.createPizza(pizzaType).getPrice()); } } }