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

本文介绍了一种通过配置文件和Factory模式实现不同接口实现类动态切换的方法。具体步骤包括创建配置文件、通过Servlet读取配置文件设置类型、利用单例模式的Factory生产不同类型的CustomerDAO实例,最终在Servlet中根据配置获取相应的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值