java web之面向接口编程

1.在类中调用接口的方法,而不关心具体的实现,有利于代码的解耦,有更好地可移植性和可扩展性!!!!!

java web之面向接口编程_第1张图片.

//2.具体的方法流程
1配置servlet---2.构建Servlet的init()方法来(获取属性值---获取type---赋予工厂类type)
//配置 
    
InitServlet    
com.mvcapp.servlet.InitServlet  
1 
 
//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 daos = new HashMap();
	
	
	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);
	}
	
}


你可能感兴趣的:(【java,web】)