静态工厂模式就是用静态方法实现的,其创建的对象具有一定的特性,譬如说是某类的派生或者某接口的实现;如:
Animal 类:
package shejimoshi.factoryMoShi.staticFactory; public abstract class Animal { private String name; public Animal() { super(); // TODO Auto-generated constructor stub } public Animal(String name) { super(); this.name = name; } public abstract void eat(); public String getName() { return name; } public void setName(String name) { this.name = name; } }
Cat 类
package shejimoshi.factoryMoShi.staticFactory; public class Cat extends Animal { public Cat() { // TODO Auto-generated constructor stub } public Cat(String name) { super(name); // TODO Auto-generated constructor stub } @Override public void eat() { System.out.println("I like to eat fish!"); } }
Dog 类:
package shejimoshi.factoryMoShi.staticFactory; public class Dog extends Animal { public Dog() { // TODO Auto-generated constructor stub } public Dog(String name) { super(name); // TODO Auto-generated constructor stub } @Override public void eat() { System.out.println("I like to eat bone!"); } }
StaticFactory 类:
package shejimoshi.factoryMoShi.staticFactory; /** * 静态工厂创建一个对象 静态工厂类产生的对象一般都有共同的特性,继承某一类,或者引用接口之类,在此 * 没有看似没有,但不可否认他们都是Object或者Object的一个子类 */ public class StaticFactory { public static Object getInstance(String className) { if ("英短".equals(className)) { return new Cat(); } else if ("拉布拉多".equals(className)) { return new Dog(); } else { return null; } } /*public static Object getInstance(String className, Object... agrs) { Class cls = null; try { cls = Class.forName(className); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block return null; } Constructor[] constructors = cls.getConstructors(); Object instance = null; for (Constructor cons : constructors) { Class<?>[] clses = cons.getParameterTypes(); if (clses.length > 0) { boolean isThisConstructor = true; for (int i = 0; i < clses.length; i++) { Class c = clses[i]; if (!c.isInstance(agrs[i])) { isThisConstructor = false; } } if (isThisConstructor) { try { instance = cons.newInstance(agrs); break; } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { continue; } } } return instance; }*/ }
Test 类:
package shejimoshi.factoryMoShi.staticFactory; public class Test { public static void main(String[] args) { //调用getInstance()方法,返回的是一个cat/dog对象 Cat cat = (Cat) StaticFactory.getInstance("英短"); cat.eat(); System.out.println(cat); } }