工厂模式专门负责将大量有共同接口的类实例化。工厂模式可以动态决定将哪一个类实例化,
不必事先知道每次要实例化哪一个类。
简单工厂(Simple Factory)模式,又称静态工厂方法模式(Static Factory Method Pattern),是
不同的工厂方法模式的一个特殊表现
一个农场,专门生产水果, 在这个系统中需要描述以下水果
葡萄->Grape
草莓->Strawberry
苹果->Apple
建产一个各种水果都适用的接口,各种水果实现这个接口
Fruit.java
package com.archie.pattern.simplefactory; /** * 所有水果必须实现的接口 * @author archie2010 * */ public interface Fruit { /** * 生长 */ void grow(); /** * 收获 */ void harvest(); /** * 种植 */ void plant(); }
Grape.java
package com.archie.pattern.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."); } public static void log(String msg){ System.out.println(msg); } public boolean isSeedless() { return seedless; } public void setSeedless(boolean seedless) { this.seedless = seedless; } }
Strawberry.java
package com.archie.pattern.simplefactory; public class Strawberry implements Fruit { public void grow() { log("Strawberry is growing..."); } public void harvest() { log("Strawberry has been harvested."); } public void plant() { log("Strawberry has been planted."); } public static void log(String msg){ System.out.println(msg); } }
Apple.java
package com.archie.pattern.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."); } /** * 辅助方法 * @param msg */ public static void log(String msg){ System.out.println(msg); } public int getTreeAge() { return treeAge; } public void setTreeAge(int treeAge) { this.treeAge = treeAge; } }
FruitGardener.java
package com.archie.pattern.simplefactory; /** * 园丁类,根据客户端的要求,创建不同的水果对象 * 接到不合法的要示,会抛出BadFruitException * @author archie2010 * */ public class FruitGardener { 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"); } } }
BadFruitException.java
package com.archie.pattern.simplefactory; @SuppressWarnings("serial") public class BadFruitException extends Exception{ public BadFruitException(String msg){ super(msg); } }
Main.java(测试)
package com.archie.pattern.simplefactory; public class Main { /** * @param args * @throws BadFruitException */ @SuppressWarnings("static-access") public static void main(String[] args) { FruitGardener gardener=new FruitGardener(); Fruit fruit; try { fruit = gardener.factory("apple"); fruit.plant(); fruit.grow(); fruit.harvest(); } catch (BadFruitException e) { e.printStackTrace(); } } }
Console:
Apple has been planted.
Apple is growing...
Apple has been harvested.