1. servlet中与要实现的用户业务逻辑 未解耦之前: 在Servlet中:Userservice us = new UserServiceImpl();//需要指定实例化具体的哪一个对象 , 产生了耦合(Uservice是接口) 解耦之后: UserService us = BaseFactory.getFactory().getInstance(UserService.class);//并没有指定具体的对象 , 而是由工厂类从配置文件中读取配置具体的实现类 ,没有耦合 2. 配置文件config.properties中的内容:UserService=com.tj.service.UserServiceImpl.java 3. 工厂类实现: public class BaseFactory { private static BaseFactory base = new BaseFactory(); private static Properties prop = new Properties(); static{ try { String path = BaseFactory.class.getClassLoader().getResouce("config.properties").getPath(); prop.load(new FileInputStream(path)); } catch (Exception e) { e.printStackTrace(); } } private BaseFactory(){} public static BaseFactory getBase(){ return base; } public <T>T getInstance(Class<T> clz) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ //读取配置文件中的属性 String name= prop.getProperty(clz.getSimpleName()); return (T) Class.forName(name).newInstance(); } } |
|