抽象工厂模式:创建一些列相关或者互相依赖的对象的接口,而无需指定他们具体的类,
1、创建工厂Factory:
package patterns.design.factory; import java.io.InputStream;
import java.util.Properties; public class DaoFactory { // 单例
private DaoFactory(){ try {
// 读配置文件获得实现类 类名
Properties props = new Properties();
InputStream in = DaoFactory.class.getClassLoader()
.getResourceAsStream("dao.properties");
props.load(in); this.employeeDaoClassname = props.getProperty("employeeDaoClassname"); } catch (Exception e) {
throw new ExceptionInInitializerError(e);
} } private static DaoFactory instance = new DaoFactory(); public static DaoFactory newDaoFactory() {
return instance;
} private String employeeDaoClassname; // 提供方法返回实例对象dao
public EmployeeDao newEmplyeeDao() {
try {
// 反射创建对象
EmployeeDao employeeDao = (EmployeeDao) Class.forName(
this.employeeDaoClassname).newInstance();
return employeeDao;
} catch (Exception e) {
throw new RuntimeException(e);
}
} }
2.在service中调用工厂类创建对象
package patterns.design.factory; import java.util.List; public class BusinessService { // service 的方法取决于功能
private EmployeeDao employeeDao; public BusinessService() {
// 自己创建对象
// 调用 工厂类获得一个dao对象
this.employeeDao = DaoFactory.newDaoFactory().newEmplyeeDao();
} //查看所有员工
public List getAllEmployees() {
return employeeDao.getAll();
} }
3.dao.properties
employeeDaoClassname=patterns.design.factory.EmployeeDaoImpl
4.EmployeeDao.java
package patterns.design.factory;
import java.util.List;
public interface EmployeeDao {
public List getAll();
}