工厂模式实现简介:
1.工厂模式定义了统一的接口和众多实现类,工厂模式生成实现类对象的方式是通过定义的ClassUtils中静态方法getAllClassByInterface(Class c)实现的,
1.首先获传入的接口全路径包名 // c.getPackage().getName();
2.通过类加载机制获取列表文件信息
3.通过文件信息反射创建类对象
代码示例如下:
1.接口Human
2.接口实现类:(这里只贴出一个其他类实现方式相同)
3.工厂的实现
public class FactoryHuman { public static Human createHuman(Class c) { Human human = null; try { human = (Human)Class.forName(c.getName()).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return human; } public static Human createHuman(){ Human human = null; List<Class> concreteHumanList = ClassUtils.getAllClassByInterface(Human.class); Random random = new Random(); int rand = random.nextInt(concreteHumanList.size()); human = createHuman(concreteHumanList.get(rand)); return human; } }
4.重要实现类ClassUtils
public class ClassUtils { // 通过接口获得类集合 public static List<Class> getAllClassByInterface(Class c) { List<Class> returnClassList = new ArrayList<Class>(); if (c.isInterface()){ String packageName = c.getPackage().getName(); System.out.println(packageName); try { List<Class> allClass = null; try { allClass = getClasses(packageName); } catch (ClassNotFoundException e) { e.printStackTrace(); } for (int i = 0 ;i<allClass.size();i++){ if (!c.equals(allClass.get(i))){ returnClassList.add(allClass.get(i)); } } } catch (IOException e) { e.printStackTrace(); } } return returnClassList; } // 获取类集合 private static List<Class> getClasses(String packageName) throws IOException, ClassNotFoundException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); System.out.println(packageName+"----------------"); String path = packageName.replace(".","/"); System.out.println("path :"+ path); Enumeration<URL> resources = classLoader.getResources(path); System.out.println("resource = "+resources); List<File> dirs = new ArrayList<File>(); while (resources.hasMoreElements()){ URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class> classes = new ArrayList<Class>(); for (File directory :dirs){ System.out.println("directory : "+directory); classes.addAll(findClasses(directory,packageName)); } return classes; } // 根据目录、包名反射得到类 private static Collection<? extends Class> findClasses(File directory, String packageName) throws ClassNotFoundException { List<Class> classes = new ArrayList<Class>(); if (!directory.exists()){ return classes; } File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()){ assert !file.getName().contains(".");//断言 判断语法为真 若为false则 抛出异常 classes.addAll(findClasses(file,packageName+"."+file.getName())); }else if (file.getName().endsWith(".class")){ classes.add(Class.forName(packageName+"."+file.getName().substring(0,file.getName().length() - 6))); } } return classes; } }