思路:
1.先创建两个接口及其实体类
package com.cn.dao;
public class BeanDaoImpl implements BeanDao{
@Override
public int update() {
System.out.println("BeanDaoImpl:获取成功");
return 0;
}
}
package com.cn.server;
public class BeanServerImpl implements BeanServer{
@Override
public int update() {
System.out.println("BeanServer:获取成功");
return 0;
}
}
2.创建简单的配置文件bean.properties
beanDao=com.cn.dao.BeanDaoImpl
beanService=com.cn.server.BeanServerImpl
3.开始创建工厂对象:
(1)实例化一个properties对象用于读取配置文件
(2)在工厂对象的构造方法中加载配置文件的路径
(3)开始写Object getBean(String name)方法,参数:要获取的对象名,返回值:Object
利用properties对象获取对应对象的全路径,利用反射原理创建该对象并返回
(4)测试类测试
代码如下:
工厂对象代码:
package com.cn.factory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MyFactory {
private Properties props = new Properties();
public MyFactory() throws IOException {
InputStream in = MyFactory.class.getResourceAsStream("/bean.properties");
props.load(in);
}
public Object getBean(String name) throws Exception {
String property = props.getProperty(name);
Class<?> cls = Class.forName(property);
return cls.newInstance();
}
}
测试类代码: