工厂模式:降低层与层之间的耦合度
工程模式的组成:接口、配置文件、工厂。
1)接口定义及接口的实现类
2)配置文件:将接口与接口的具体实现类以键值对的形式存储
如:src目录下新建bean.properties文件,写入
UserEngine=com.uc.lottery.engine.impl.UserEngineImpl
等等。。。
3)工厂类创建:通过调用者传递的接口信息,在配置文件中获取对应的实现类,并创建实例返回。
<span style="font-size:18px;">public class BeanFactory {
// 依据配置文件加载实例
private static Properties properties;
static{
properties = new Properties();
try {
// bean.properties文件必须放在src目录下
properties.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 加载需要的实现类
* @param clazz
* @return
*/
public static <T> T getImpl(Class<T> clazz){
String key = clazz.getSimpleName();
String implClassName = properties.getProperty(key);
try {
return (T) Class.forName(implClassName).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}</span>