//源代码地址:http://download.csdn.net/detail/a17909863341/5321145
package org.ustc.abstractfactory; public class DataAccess { public static final String db = "org.ustc.abstractfactory.Access"; public static final String USER = "User"; public static final String DEPARTMENT = "Department"; public static UserInterface createUser(){ UserInterface user = null; try { user = (UserInterface) Class.forName(db+USER).newInstance();//反射 } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return user; } public static DepartmentInterface createDepart(){ DepartmentInterface depart = null; try { depart = (DepartmentInterface) Class.forName(db+DEPARTMENT).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return depart; } }
package org.ustc.abstractfactory; public class SimpleFactory {//简单工厂 public static String USER = "sql"; public static UserInterface createUser(){ UserInterface user = null; switch(USER.charAt(0)){ case 's': user = new SqlUser(); break; case 'a': user = new AccessUser(); break; } return user; } public static DepartmentInterface createDepartment(){ DepartmentInterface depart = null; switch(USER.charAt(0)){ case 's': depart = new SqlDepartment(); break; case 'a': depart = new AccessDepartment(); break; } return depart; } }
package org.ustc.abstractfactory; public interface AbstractFactory {//抽象工厂 public UserInterface createUser(); public DepartmentInterface createDepartment(); }
package org.ustc.abstractfactory; public class AccessFactory implements AbstractFactory{ @Override public UserInterface createUser() { // TODO Auto-generated method stub return new AccessUser(); } @Override public DepartmentInterface createDepartment() { // TODO Auto-generated method stub return new AccessDepartment(); } }
package org.ustc.abstractfactory; public class SqlFactory implements AbstractFactory { @Override public UserInterface createUser() { // TODO Auto-generated method stub return new SqlUser(); } @Override public DepartmentInterface createDepartment() { // TODO Auto-generated method stub return new SqlDepartment(); } }
package org.ustc.abstractfactory; public interface DepartmentInterface { public void getDepartmentById(int id) ; public void InsertDepartment(Department dept); }
package org.ustc.abstractfactory; public interface UserInterface { public void getUserById(int id) ; public void InsertUser(User user); }
简单工厂代码结构图
大话设计模式 抽象工厂
最新推荐文章于 2019-01-17 09:02:02 发布