MVC案例——通过配置切换底层存储源

mac2022-06-30  77

深入理解面向接口编程:在类中调用接口的方法,而不必关心具体的实现。这将有利于代码的解耦。使程序有更好的可移植性和可扩展性

 

1)动态修改Customer的存储方式:通过修改类路径下的switch.properties文件的方式来实现

2)CustomerServlet中不能在通过private CustomerDAO customerDAO = new CustomerDAOXMLImpl();的方式来写死实现类

3)通过一个类的一个方法来获取具体的实现类对象

当前WEB应用启动的时候,InitServlet被创建,并由Servlet容器调用其init()方法:

1)读取类路径下的switch.properties文件

2)获取switch.properties的type属性值

3)赋给CustomerDAOFactory的type属性值

创建CustomerServlet时,为customerDAO属性赋值是通过CustomerDAOFactory的getCustomerDAO()方法完成的。

 

CustomerDAOFactory

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

转载于:https://www.cnblogs.com/yangHS/p/11150985.html

最新回复(0)