package us.deans.pigs.client; import us.deans.pigs.api.Wolf; import us.deans.pigs.api.Pig; import us.deans.pigs.api.AnimalFactory; import org.apache.log4j.Logger; public class Chapters { AnimalFactory aFactory1 = null; private Logger logger = Logger.getLogger(Chapters.class); // AminalFactory - constructor injection (one instance of this class will always be needed). public Chapters(AnimalFactory aFactory) { this.aFactory1 = aFactory; } // meet the wolf -- factory public void chapter_01(){ logger.info("\n\nChapter 1 : Once upon a time, there was this wolf...\n"); try { Wolf wolf = (Wolf) aFactory1.getMe("a wolf"); } catch(Exception ex){ logger.info("Here..." + ex.getMessage()); logger.info("And this too..." + ex.getStackTrace()); } logger.info("A hungry wolf... a baaad wolf..."); } // the house of straw -- factory public void chapter_02() { // welcome logger.info("\n\nChapter 2 : Meanwhile, the first pig builds a house...\n"); // see the pig -- using factory that was itself injected through the client. try{ Pig pig = (Pig) aFactory1.getMe("a pig"); pig.gather("straw"); pig.buildHouse(); } catch (Exception ex) { logger.info("Here..." + ex.getMessage()); logger.info("And this too..." + ex.getStackTrace()); } logger.info("Oh, oh... here comes the wolf!"); logger.info("The pig runs like hell toward the woods, where his brother lives"); } // the house of sticks -- constructor injection public void chapter_03() { logger.info("\n\nChapter 3 : ...Just so happens the second pig was also building a house...\n"); // see the pig try{ Pig pig = (Pig) aFactory1.getMe("a pig"); pig.gather("sticks"); pig.buildHouse(); } catch (Exception ex) { logger.info("Here..." + ex.getMessage()); logger.info("And this too..." + ex.getStackTrace()); } logger.info("The first pig shows up and is glad to see his brother's house."); logger.info("Hide inside... here comes the wolf!"); } // the house of bricks -- using reflection public void chapter_04() { logger.info("\n\nChapter 4 : The third pig builds a house too...\n"); // see the pig try{ Object aFactory = Class.forName("us.deans.pigs.api.AnimalFactory").newInstance(); Pig pig = (Pig) ((AnimalFactory) aFactory).getMe("a pig"); pig.gather("bricks"); pig.buildHouse(); } catch (Exception ex) { logger.info("Here..." + ex.getMessage()); logger.info("And this too..." + ex.getStackTrace()); } logger.info("Oh, oh... here comes the wolf!"); } }