设计模式--工厂模式

1.bean.xml

<?xml version="1.0" encoding="UTF-8"?>

 <beans>
     <bean id="bookService" class="com.book.service.BookServiceimpl" scope="singleton"></bean>
     <bean id="loginService" class="com.book.service.LoginServiceimpl"></bean>
 </beans>

2.beanConfig.java实体

package com.book;

public class BeanConfig {
	
	public String id;
	public String clazz;
	public String scope;
	public BeanConfig() {
		super();
	}
	public BeanConfig(String id, String clazz, String scope) {
		super();
		this.id = id;
		this.clazz = clazz;
		this.scope = scope;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getClazz() {
		return clazz;
	}
	public void setClazz(String clazz) {
		this.clazz = clazz;
	}
	public String getScope() {
		return scope;
	}
	public void setScope(String scope) {
		this.scope = scope;
	}
	@Override
	public String toString() {
		return "BeanConfig [id=" + id + ", clazz=" + clazz + ", scope=" + scope + "]";
	}
	
	
	

}

3.beanFactory.java工厂类

package com.book.common;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.book.BeanConfig;

/**
 * 用于解析bean.xml文件
 * 封装成BeanConfig.java实体
 * @author y
 *
 */
public class BeanFactory {
	
	private static Map<String, BeanConfig> beans = new HashMap<String, BeanConfig>();
	
	private static Map<String,Object> objects = new HashMap<String, Object>();
	
	
	//类加载时生成beanFactory
	private static BeanFactory beanFactory;
	//构造私有化
	private BeanFactory() {};
	
	public static BeanFactory getInstance() {
		if(beanFactory==null) {
			beanFactory=new BeanFactory();
			beanFactory.init();
		}
		return beanFactory;
	}
	
	private void init() {
		// TODO Auto-generated method stub
		System.out.println("------进入beanFactory的init方法------开始解析bean.xml");
		InputStream in = null;
		in = BeanFactory.class.getClassLoader().getResourceAsStream("com/book/bean.xml");
		DocumentBuilderFactory Dofactory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder =  Dofactory.newDocumentBuilder();
			Document document = builder.parse(in);
			Element element =  document.getDocumentElement();
			NodeList beanNode = element.getElementsByTagName("bean");
			if(beanNode==null) {
				return ;
			}
			int beanLength = beanNode.getLength();
			for(int i=0;i<beanLength;i++) {
				Element beanEle = (Element) beanNode.item(i);
				BeanConfig bean = new BeanConfig();
				String id = beanEle.getAttribute("id");
				bean.setId(id);
				
				String classname = beanEle.getAttribute("class");
				bean.setClazz(classname);

				String scope = beanEle.getAttribute("scope");
				bean.setScope(scope);
				
				beans.put(id, bean);
				System.out.println("beanConfig---------------"+bean);
			}
			
			
		} catch (ParserConfigurationException | SAXException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(in !=null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		
		
	}

	public Object getBean(String id) {
		Object obj=null;
		
		if(beans.containsKey(id)) {
			BeanConfig bean = beans.get(id);
			String scope = bean.getScope();
			if(scope==null || scope.equals("")) {
				scope="singleton";
			}
			if(scope.equals("singleton")) {
				if(objects.containsKey(id)) {
					return objects.get(id);
				}
			}
			String clssName = bean.getClazz();
			Class<?> claz = null;
			
			try {
				claz = Class.forName(clssName);
				obj = claz.newInstance();
				System.out.println("创建的对象="+obj);
				
				if(scope.equalsIgnoreCase("singleton")) {
					objects.put(id, obj);
				}
				
				
				
			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return obj;
	}
	
}

4.取代new关键字

package com.book.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Constants;
import com.book.exception.ServiceException;
import com.book.common.BeanFactory;
import com.book.dao.LoginDao;
import com.book.dao.LoginDaoimpl;
import com.book.entity.User;
import com.book.exception.ParaException;
import com.book.service.LoginService;
import com.book.service.LoginServiceimpl;

public class LoginServlet extends HttpServlet {
	
	//private LoginService loginService = new LoginServiceimpl();
	/**
	 * 替代new关键字,使用BeanFactory
	 */
	private LoginService loginService =(LoginService) BeanFactory.getInstance().getBean("loginService");
	
	
	private final String  WELCOME_PATH="/WEB-INF/jsp/welcome.jsp";
	private final String  LOGIN_PATH="/WEB-INF/jsp/login2.jsp";
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher(LOGIN_PATH).forward(request, response);
		
		
	}
		
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值