抽象工厂模式(Abstract Factory),提供一个创建一系列相关或相互依赖对象的接口,而无需指定他们具体的类。
所有在用简单工厂的地方,都可以考虑用反射技术,搭配配置文件去除switch 或 if,解除分支判断带来的耦合。
(C#)Assembly.load("程序集名称").CreateInstance(""命名空间.类名称)。
package abstractFactor; public class User { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } }
package abstractFactor; public class Department { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } }
package abstractFactor; public interface ITest<T> { void Insert(T object); T getObject(String id); }
package abstractFactor; public class SqlserverUser implements ITest<User> { @Override public void Insert(User object) { System.out.println("SqlserverUser Insert"); } @Override public User getObject(String id) { System.out.println("SqlserverUser getObject"); return null; } }
package abstractFactor; public class OracleUser implements ITest<User> { @Override public void Insert(User object) { System.out.println("OracleUser Insert"); } @Override public User getObject(String id) { System.out.println("OracleUser getObject"); return null; } }
package abstractFactor; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class DataAccess { private static String db = "Sqlserver"; public static ITest<User> createUser() { String className = "abstractFactor."+db + "User"; System.out.println(className); Class<ITest<User>> clazz; Constructor<ITest<User>> constructor = null; try { // 获得类对象 clazz = (Class<ITest<User>>) Class.forName(className); // 获得构造器 constructor = clazz.getConstructor(null); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { // 创建对象 return (ITest<User>) constructor.newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } public static void main(String[] args) { User user=new User(); ITest<User> iu=DataAccess.createUser(); iu.Insert(user); iu.getObject("1"); } }