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

1、创建工厂Factory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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 }

 

posted on   张释文  阅读(237)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示