以水果为例讲解简单工厂模式,其中有三种水果,
*葡萄 Grape
*草莓Strawberry
*苹果Apple
水果并无具体的对象,因此是一个各个水果都适用的接口,以便与其他植物分隔开来。
三种水果均有自己不同的属性,现在实现水果接口及其三种水果的源码。
Fruit:
package SimpleFactory; public interface Fruit { /** * 生长 */ void grow(); /** * 收获 */ void harvest(); /** * 种植 */ void plant(); }Apple:
package SimpleFactory; public class Apple implements Fruit { private int treeAge; //苹果树的树龄 @Override public void grow() { log("Apple is growing"); } @Override public void harvest() { log("Apple has been harvested"); } @Override public void plant() { log("Apple has been planted"); } public int getTreeAge() { return treeAge; } public void setTreeAge(int treeAge) { this.treeAge = treeAge; } private void log(String msg){ System.err.println(msg); } }Grape:
package SimpleFactory; public class Grape implements Fruit { private boolean seedless; //葡萄有籽或者无籽 @Override public void grow() { log("Grape is growing..."); } @Override public void harvest() { log("Grape has been harvested"); } @Override public void plant() { log("Grape has been planted"); } private void log(String msg){ System.err.println(msg); } public boolean isSeedless() { return seedless; } public void setSeedless(boolean seedless) { this.seedless = seedless; } }Strawberry:
package SimpleFactory; public class Strawberry implements Fruit { @Override public void grow() { log("Strawberry is growing..."); } @Override public void harvest() { log("Strawberry has been harvested."); } @Override public void plant() { log("Strawberry has been planted"); } private void log(String msg){ System.err.println(msg); } }
实现这三种水果后,还需要一个园丁来照料他们,因此还有一个园丁类,源码为:
package SimpleFactory; public class FruitGardener { /** * 静态工厂方法 * @param which * @return */ public static Fruit 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"); } } }里面有一个BadException,当出现在园子中没有出现的水果时,要抛出异常,因此还有一个异常类。
BadException:
package SimpleFactory; public class BadFruitException extends Exception { public BadFruitException(String msg){ super(msg); } }当这些都实现后,便可使用此模式进行收获,源码为:
package SimpleFactory; public class Client { public static void main(String[] args) { try { FruitGardener.factory("grape"); FruitGardener.factory("apple"); FruitGardener.factory("strawberry"); } catch (BadFruitException e) { } } }
如此,便实现简单的工厂模式。
原文地址:http://blog.csdn.net/u012734441/article/details/43917211