zoukankan      html  css  js  c++  java
  • MVC案例——通过配置切换底层存储源

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

    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);
        }
    }
  • 相关阅读:
    设计模式-装饰器模式
    自定义 RestTemplate 异常处理 (转)
    Jackson 高级应用
    Jackson 的 基本用法
    Jackson转换为Collection、Array
    Jackson中处理map中的null key 或者null value 及实体字段中的null value
    sed
    MySQL server has gone away 异常
    nl命令
    线程池
  • 原文地址:https://www.cnblogs.com/yangHS/p/11150985.html
Copyright © 2011-2022 走看看