1.简单工厂模式
简单工厂模式(Simple Factory Pattern)属于类的创新型模式,又叫静态工厂方法模式(Static FactoryMethod Pattern),是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
2.普通实现
1.抽象产品接口:Animal
2.静态工厂:AnimalFactory
package com.sgl.model.create.simplefactory; /** * Animal工厂类,提供静态getAnimal方法,获取具体的产品实例 * * @author sgl * */ public class AnimalFactory { public static Animal getAnimal(String witch) { if (witch.equalsIgnoreCase("Dog")) { return new Dog(); } else if (witch.equalsIgnoreCase("cat")) { return new Cat(); } return null; } }
package com.sgl.model.create.simplefactory; /** * 动物(产品接口),定义公共的行为 * @author sgl * */ public interface Animal { void eat(); void grow(); }
package com.sgl.model.create.simplefactory; /** * Dog实现Animal接口,并重写eat和grow方法 * * @author sgl * */ public class Dog implements Animal{ @Override public void eat() { System.out.println("吃骨头"); } @Override public void grow() { System.out.println("吃骨头,长大"); } }
package com.sgl.model.create.simplefactory; /** * Cat实现Animal接口,并重写eat和grow方法 * * @author sgl * */ public class Cat implements Animal { @Override public void eat() { // TODO Auto-generated method stub System.out.println("吃鱼"); } @Override public void grow() { // TODO Auto-generated method stub System.out.println("吃鱼长大"); } }
3.利用反射构建简单工厂模式
思路:
1.提供一个产品接口,并未声明该接口的任何方法,仅作为类型使用
2.提供一个工厂类,并提供一个静态工厂方法,参数为需要被创建对象的全限定名,返回对象实例
package com.sgl.model.create.simplefactory; /** * 提供产品的父类模板接口 * @author sgl * */ public interface ObjectTemplate { }
package com.sgl.model.create.simplefactory; /** * 静态工厂类 * @author sgl * */ public class SimpleFactoryTmplate { /** * 通过类的全限定名来获取对象实例 * @param className 全限定名 * @throws ClassNotFoundException * @throws InstantiationException * @throws IllegalAccessException */ public static ObjectTemplate SimpleObjectFactory(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { return (ObjectTemplate) Class.forName(className).newInstance(); } }
测试:
package com.sgl.model.create.simplefactory; public class Apple implements ObjectTemplate{ private int treeAge; public int getTreeAge() { return treeAge; } public void setTreeAge(int treeAge) { this.treeAge = treeAge; } public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Apple apple=(Apple) SimpleFactoryTmplate.SimpleObjectFactory("com.sgl.model.create.simplefactory.Apple"); System.out.println(apple.getTreeAge()); } }
返回结果:0(未设置treeAge的值,返回默认值为0)
用途:
定义一个类实现ObjectTemplate,通过将该类的全限定名作为参数传入获取实例对象,该方式可避免扩展时修改SimpleFactoryTmplate类中的静态方法。