【代码积累】replace constructor with factory method

import java.lang.reflect.InvocationTargetException;
/*典型的遵循OCP原则的编程技巧,结合了继承,反射;
 * 适用于需要大量创建同一族对象的场合,即,这些对象有共同的父类,但是各自类型不同;
 * 通常情况下,如果使用子类的构造器构造,需要在create方法中放置一个switch结构,当需要增加子类类型时,不便于扩展;
 * 使用反射,则只需要根据入参自动创建,创建对象部分的代码可以复用,不需要修改;
 * 带来的弊端是如果指定类型名称错误,或者类型不存在,则会创建失败,使用replace parameters with methods规避,但会带来维护工作量*/

public class Test {
	public void test() {
		PersonFactory pFac = new PersonFactory();
		Person mike = pFac.create("Mike", "Salesman");
		Person kate = pFac.create("Kate", "Teacher");
		
		System.out.println("Mike:name="+mike.getName()+",vocation="+mike.getVocation());
		System.out.println("Kate:name="+kate.getName()+",vocation="+kate.getVocation());
	}
	
	public class PersonFactory {
		public Person create(String name,String vocation) {
			Person person = null;
			
			try {
				/*Class.forName must use the fully qualified name of the class*/
				person =  (Person)(Class.forName(vocation).getDeclaredConstructor(String.class).newInstance(name));
			} catch (InstantiationException | IllegalAccessException
					| IllegalArgumentException | InvocationTargetException
					| NoSuchMethodException | SecurityException
					| ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return person;
		}
		
		//replace parameters with methods
		public Salesman createSalesman(String name) {
			return new Salesman(name);
		}
	}
}

你可能感兴趣的:(【代码积累】replace constructor with factory method)