对工厂模式的认识和理解(一)

1.
package com.ethan.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

//使用dom4j解析xml,自己加入jar、import
public class DaoFactory {
        //设置一个DAO缓冲池
	private Map daoMap = new HashMap();
	
	private static DaoFactory df;
	
	private DaoFactory(String path) throws Exception {
		
		//path 可以用System.getProperty("user.dir")+ package + xml 组合一下,因为xml放在package下边了
		Document doc = new SAXReader().read(new File(path+"\\daoContext.xml"));
		
		Element root = doc.getRootElement();
		List el = root.elements();
		
		for(Iterator it = el.iterator();it.hasNext()) {
			Element element = (Element)it.next();
			String id = element.attributeValue("id");
			String impl = element.attributeValue("class");
			
			Class clazz = Class.forName(impl);
			
			Object obj = clazz.newInstance();
			
			daoMap.put(id, obj);
		}
	}
	
        //实例化DAO Factory
	public static DaoFactory instance(String path) throws Exception {
		if(df==null) {
			df = new DaoFactory(path);
		}
		return df;
	}
	
 //获取DAO实例
	public Object getDAO(String id) {
		return daoMap.get(id);
	}
}
daoFactory.xml:


	
	

2.
package com.ethan.dao;


public interface UserDAO {
	
}
package com.ethan.dao;


public class UserDAOImpl implements UserDAO {
	
}
package com.ethan.dao;


public class FactoryDAO {
	public UserDAO createUserDAO() {
		return new UserDAOImpl();
	}
}
如果以后换了UserDao的实现,是需要改变 createDAOImpl(), 业务逻辑代码无需改变。好处不言而喻。

你可能感兴趣的:(dp设计模式)