package start2_3.ducks; import java.util.*; /** * Author: Josiah Yoder et al. * Class: SE1011-011 * Date: 12/10/13 8:41 AM * Lesson: Week 7, Day 1 */ public abstract class DuckCreator { public static final int NO_DUCK = Integer.MAX_VALUE; public static final int FINISHED = 0; /** * Mapping from int duckType to the creator for the duck we are looking for. */ private static Map creatorMap = new Hashtable(); public static void runApplication() { Scanner in = new Scanner(System.in); List ducks = DuckCreator.createDucks(in); System.out.println(""); System.out.println("Ducks entered:"); for(Duck duck : ducks) { System.out.println(duck); } System.out.println(""); System.out.println("Swim, ducks, swim:"); for(Duck duck : ducks) { duck.swim(); } } /** * Register a new duck type with the Duck Creator * @param duckType "key" for the new type. Must not be in use yet. * @param creator an instance of the DuckCreator class with its own implementation of createDuck() */ public static void addDuck(int duckType, DuckCreator creator) { if(FINISHED == duckType || NO_DUCK == duckType || creatorMap.containsKey(duckType)) { throw new IllegalArgumentException("Key "+ duckType +" is already taken."); } creatorMap.put(duckType, creator); } public static List createDucks(Scanner in) { List ducks = new ArrayList(); int duckType = NO_DUCK; while(duckType != FINISHED) { System.out.println("Please enter a duck type: "); System.out.println(" 0. Exit"); for (Map.Entry entry : creatorMap.entrySet()) { System.out.printf("% 2d: %s", entry.getKey(), entry.getValue().getMenuName()); System.out.println(); } duckType = in.nextInt(); if( duckType != FINISHED) { ducks.add(createDuck(duckType, in)); } } return ducks; } /** * Create a new instance of the duck class. * @param in The input * @return The newly-created duck */ public static Duck createDuck(int duckType, Scanner in) { DuckCreator creator; if(creatorMap.containsKey(duckType)) { creator = creatorMap.get(duckType); } else { throw new IllegalArgumentException("Unsupported duck type: "+duckType); } return creator.createDuck(in); } /** * * This is the factory method. * * Each duck should override it to create its own duck types. * * @param in */ public abstract Duck createDuck(Scanner in); /** * * Returns the name of the specific duck type to be printed in the menu * * @return the name of the duck to be printed in the menu */ public abstract String getMenuName(); }