1. servlet中與要實(shí)現(xiàn)的用戶業(yè)務(wù)邏輯未解耦之前:在Servlet中:Userservice us = new UserServiceImpl();//需要指定實(shí)例化具體的哪一個(gè)對(duì)象 , 產(chǎn)生了耦合(Uservice是接口)解耦之后:UserService us = BaseFactory.getFactory().getInstance(UserService.class);//并沒(méi)有指定具體的對(duì)象 , 而是由工廠類(lèi)從配置文件中讀取配置具體的實(shí)現(xiàn)類(lèi) ,沒(méi)有耦合2. 配置文件config.properties中的內(nèi)容:UserService=com.tj.service.UserServiceImpl.java3. 工廠類(lèi)實(shí)現(xiàn): 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(); }}
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。