1. 程式人生 > >java web之面向介面程式設計

java web之面向介面程式設計

1.在類中呼叫介面的方法,而不關心具體的實現,有利於程式碼的解耦,有更好地可移植性和可擴充套件性!!!!!

.

//2.具體的方法流程
1配置servlet---2.構建Servlet的init()方法來(獲取屬性值---獲取type---賦予工廠類type)
//配置 
<servlet>    
<servlet-name>InitServlet</servlet-name>    
<servlet-class>com.mvcapp.servlet.InitServlet</servlet-class>  
<load-on-startup>1</load-on-startup> 
 </servlet>
//init()方法
public void init() throws ServletException {
CustomerDAOFactory.getInstance().setType("jdbc");
//讀取類路徑下的 switch.properties 檔案
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/switch.properties");
Properties properties = new Properties();
try {properties.load(in);
//獲取 switch.properties 的 type 屬性值
String type = properties.getProperty("type");
//賦給了 CustomerDAOFactory 的 type 屬性值
CustomerDAOFactory.getInstance().setType(type);
} catch (Exception e) {e.printStackTrace();}}

工廠方法

public class CustomerDAOFactory {
	
	private Map<String, CustomerDAO> daos = new HashMap<String, CustomerDAO>();
	
	
	private static CustomerDAOFactory instance = new CustomerDAOFactory();
	
	public static CustomerDAOFactory getInstance() {
		return instance;
	}
	
	private String type = null;
	
	public void setType(String type) {
		this.type = type;
	}
	
	private CustomerDAOFactory(){
		daos.put("jdbc", new CustomerDAOJdbcImpl());
		daos.put("xml", new CustomerDAOXMLImpl());
	}
	
	public CustomerDAO getCustomerDAO(){
		return daos.get(type);
	}
	
}