03.设计模式_抽象工厂模式(Abstract Fcatory)

抽象工厂模式:创建一些列相关或者互相依赖的对象的接口,而无需指定他们具体的类,

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中调用工厂类创建对象

 1 package patterns.design.factory;
 2 
 3 import java.util.List;
 4 
 5 
 6 public class BusinessService {
 7     
 8     // service 的方法取决于功能
 9     private EmployeeDao employeeDao;
10     
11     public BusinessService() {
12         // 自己创建对象
13         // 调用 工厂类获得一个dao对象
14         this.employeeDao = DaoFactory.newDaoFactory().newEmplyeeDao();
15     }
16     
17 
18     //查看所有员工
19     public List getAllEmployees() {
20         return employeeDao.getAll();
21     }
22 
23     
24 }

3.dao.properties

employeeDaoClassname=patterns.design.factory.EmployeeDaoImpl

4.EmployeeDao.java

1 package patterns.design.factory;
2 import java.util.List;
3 public interface EmployeeDao {
4     public List getAll();
5 }
原文地址:https://www.cnblogs.com/zhangshiwen/p/4349232.html