工厂方法设计模式:定义一个用于创建对象的接口,让子类来决定来创建具体的对象。在类的结构上,对象子类与工厂子类是平行关系的。
下面我们看一个简单的例子:
package net.itaem.create; /** * 接口:代表工厂要生产的对象 * */ public interface Fruit { public void name(); public void price(); }
package net.itaem.create; /** * 具体的产品 * */ public class Apple implements Fruit{ @Override public void name() { System.out.println("the product name is apple"); } @Override public void price() { System.out.println("the apple price is 10"); } }
package net.itaem.create; /** * 具体的产品 * */ public class Banana implements Fruit { @Override public void name() { System.out.println("the product is Banana"); } @Override public void price() { System.out.println("the banana price is 10"); } }
package net.itaem.create; /** * 定义一个工厂类,每个Concrete Factory负责生产具体的对象 * */ public abstract class FruitFactory { public abstract Fruit create(); }
package net.itaem.create; public class AppleFactory extends FruitFactory{ @Override public Fruit create() { return new Apple(); } }
package net.itaem.create; public class BananaFactory extends FruitFactory{ @Override public Fruit create() { return new Banana(); } }
package net.itaem.create; public class FactoryManager { private FruitFactory factory; /** * 通过配置文件,读取具体的Factory对象 * */ public FactoryManager(FruitFactory factory){ this.factory = factory; } public void setFruitFactory(FruitFactory factory){ this.factory = factory; } public Fruit create(){ return factory.create(); } public static void main(String[] args) { System.out.println("-----------------------apple ---------------- "); FactoryManager fruitFactory = new FactoryManager(new AppleFactory()); Fruit fruit = fruitFactory.create(); fruit.name(); fruit.price(); System.out.println("-----------------change to banana-------------------"); <span style="color:#ff0000;">fruitFactory.setFruitFactory(new BananaFactory()); fruit = fruitFactory.create(); fruit.name(); fruit.price(); } }
-----------------------apple ---------------- the product name is apple the apple price is 10 -----------------change to banana------------------- the product is Banana the banana price is 10
类图结构:
总结:工厂方法是一种灵活的设计方式,该设计模式相对于静态工厂设计模式的最大优点就是,可以方便的扩展新的子类。
缺点:如果类过多,工厂对象的继承结构将会出现庞大的类。比如有1000种水果,那么就会有1000个工厂。
原文地址:http://blog.csdn.net/u010469003/article/details/26718521