| package com.javapatterns.simplefactory; public class FruitGardener { public FruitIF factory(String which) throws BadFruitException { if (which.equalsIgnoreCase("apple")) { return new Apple(); } else if (which.equalsIgnoreCase("strawberry")) { return new Strawberry(); } else if (which.equalsIgnoreCase("grape")) { return new Grape(); } else { throw new BadFruitException("Bad fruit request"); } } } |
| package com.javapatterns.simplefactory; public class BadFruitException extends Exception { public BadFruitException(String msg) { super(msg); } } |
| try { FruitGardener gardener = new FruitGardener(); gardener.factory("grape"); gardener.factory("apple"); gardener.factory("strawberry"); ... } catch(BadFruitException e) { ... } |