通过配置文件切换接口的实现类

来源:互联网 发布:正规淘宝刷钻平台 编辑:程序博客网 时间:2024/05/22 11:33

1.首先创建配置文件 switch.properties

type=jdbc#type=xml

2.代码中获取配置文件的方式

@WebServlet(urlPatterns="/InitServlet",name="InitServlet",loadOnStartup=1)public class InitServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    @Override    public void init() throws ServletException {        CustomerDAOFactory.getInstance().setType("jdbc");        InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/switch.properties");        Properties properties = new Properties();        try {            properties.load(in);            String type = properties.getProperty("type");            CustomerDAOFactory.getInstance().setType(type);        } catch (IOException e) {            e.printStackTrace();        }    }}

3.切换接口实现类的方式,是通过Factory的方式实现的,Factory一般是单例的方式
CustomerFactory

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

4.切换接口实现类的具体代码在CustomerServlet类中:

private CustomerDAO customerDAO = CustomerDAOFactory.getInstance().getCustomerDAO();
阅读全文
1 0