首页 > 代码库 > 小例子 使用反射机制创建dao的factory

小例子 使用反射机制创建dao的factory

public class Factory {
 private static Properties props =
  new Properties();
 static{
  InputStream ips =
   Factory.class.getClassLoader()
   .getResourceAsStream(
     "util/dao.properties");
  try {
   props.load(ips);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 public static Object getInstance(String type){
  Object obj = null;
  //依据接口名称(type)找到类名
  String className = props.getProperty(type);
    try {
   Class c = Class.forName(className);
   //依据方法区中的class对象,创建
   //一个实例。
   obj = c.newInstance();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return obj;
 }
}

 

在web中调用到就可以比较方便,例如:

public class ActionServlet extends HttpServlet {

 public void service(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("utf-8");
  String uri = request.getRequestURI();
  String action = uri.substring(uri.lastIndexOf("/"),
    uri.lastIndexOf("."));
  if(action.equals("/login")){
   String username = request.getParameter(
     "username");
   String pwd = request.getParameter("pwd");
   UserDAO dao =
    (UserDAO)Factory.getInstance("UserDAO");
   try {
    User user = dao.findByUsername(
      username);
    if(user != null && user.getPwd().equals(pwd)){
     //登录成功,跳转到主功能页面
     HttpSession session =
      request.getSession();
     session.setAttribute("user", user);
     response.sendRedirect("main.jsp");
    }else{
     //登录失败,提示用户输入正确的用户名和密码
     request.setAttribute("login_error",
       "用户名或密码错误");
     request.getRequestDispatcher("login.jsp")
     .forward(request, response);
    }
   } catch (Exception e) {
    e.printStackTrace();
    throw new ServletException(e);
   }
  }
 
 }

}