com.jsj.factory====新闻发布系统(3)

2020-05-12 天气:阴天

    今天我将介绍包com.jsj.factory里面的类是做什么的:

    DaoFactory.java

    作用:dao对象创建调用这个类里面的方法,通过传递参数,会自动生成所需的对象

代码:

 

 1 package com.jsj.factory;
 2 
 3 import java.io.InputStream;
 4 import java.util.Properties;
 5 
 6 public class DaoFactory {
 7 
 8     private DaoFactory() {
 9     }
10 
11     private static Properties properties;
12 
13     static {
14         InputStream inputStream = DaoFactory.class.getClassLoader().getResourceAsStream("dao.properties");
15         properties = new Properties();
16         try {
17             properties.load(inputStream);
18         } catch (Exception e) {
19             throw new RuntimeException();
20         }
21     }
22     //静态方法直接类调用,创建AdminDao类的对象
23     public static Object getDao(String daoName){
24         try {
25             return Class.forName(properties.getProperty(daoName)).newInstance();
26         } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
27             return null;
28         }
29     }
30 
31 
DaoFactory.java

 

 

 

       ServiceFactory.java

     作用:创建相关的Service

代码:

 1 package com.jsj.factory;
 2 
 3 import java.io.InputStream;
 4 import java.util.Properties;
 5 
 6 public class ServiceFactory {
 7     //构造函数用来初始化的
 8     private ServiceFactory(){
 9     }
10 
11     private static Properties properties;
12 
13     static {
14         InputStream inputStream = DaoFactory.class.getClassLoader().getResourceAsStream("service.properties");
15         properties = new Properties();
16         try {
17             properties.load(inputStream);
18         } catch (Exception e) {
19             throw new RuntimeException();
20         }
21     }
22 
23     //创建相关的Service的对象
24     /*A a = (A)Class.forName("pacage.A").newInstance();
25     这和你
26     A a = new A();
27     是一样的效果。 */
28     public static Object getService(String serviceName){
29         try {
30             /*
31             getProperty(String key)   在此属性列表中搜索具有指定键的属性。如果在此属性列表中找不到该键,
32             则会检查默认属性列表及其默认值(递归)。如果未找到该属性,则该方法返回默认值参数。
33              */
34             return Class.forName(properties.getProperty(serviceName)).newInstance();
35         } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
36             return null;
37         }
38     }
39 
ServiceFactory.java

 

posted @ 2020-05-12 21:11  赚钱买个打印机  阅读(176)  评论(0编辑  收藏  举报