package com.heima.factory;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import com.heima.dao.UserDao;
public class DaoFactory1 {
public static void main(String[] args){//这个是工厂类,main是为了测试
DaoFactory1 factory1 = DaoFactory1.getInstance();
UserDao dao = factory1.getDao();
System.out.println(dao);
}
private static DaoFactory1 factory = new DaoFactory1();
private static UserDao userDao = null;
private DaoFactory1(){
try {
Properties prop = new Properties();
/* 此种方法不够灵活,配置文件换了位置就找不到了
InputStream is = new FileInputStream("src"+File.separator+"daoconfig.properties");
*/
InputStream is = DaoFactory1.class.getClassLoader().getResourceAsStream("daoconfig.properties");
prop.load(is);
String clazzName = prop.getProperty("userDaoClass");
System.out.println("aa"); //执行了
Class clazz = Class.forName(clazzName);
System.out.println("bb"); //执行了
UserDao user = (UserDao) clazz.newInstance();
System.out.println(user); //对象有地址
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
public static DaoFactory1 getInstance(){
return factory;
}
public static UserDao getDao(){
return userDao;
}
}
这是一个工厂类,为了实例化UserDao返回实例化对象userDao
执行结果
aa
bb
com.heima.dao.impl.UserDaoJdbcImpl@186d4c1
null
为什么最后返回是null值呢?
|
|