package com.gus.factory;
import java.io.FileReader;
import java.util.Properties;
public class BasicFactory {
private static BasicFactory basicFactory = new BasicFactory();
private static Properties properties;
private BasicFactory(){}
public BasicFactory getBasicFactory() {
return basicFactory;
}
static {
properties = new Properties();
try {
properties.load(new FileReader(BasicFactory.class.getClassLoader().getResource("config.properties").getPath()));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public <T> T getInstance(Class<T> clazz) {
try {
String cName = clazz.getSimpleName();
String cImplName = properties.getProperty(cName);
return (T)Class.forName(cImplName).newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
//在ServiceImpl中只需要这么写:
//CustomerDao customerDao = BasicFactory.getBasicFactory().getInstance(CustomerDao.class);
一般的实现解耦的工厂类:
package com.gus.factory;
import com.gus.dao.CustomerDao;
import java.io.FileReader;
import java.util.Properties;
//单例模式,需要对外提供方法
//这个工厂提供了dao层和service的解耦
public class CustomerDaoFactory {
private static CustomerDaoFactory customerDaoFactory = new CustomerDaoFactory();
private static Properties properties = null;
private CustomerDaoFactory() {
}
public static CustomerDaoFactory getCustomerFactory() {
return customerDaoFactory;
}
// 读取配置文件
static {
properties = new Properties();
try {
properties.load(new FileReader(CustomerDaoFactory.class.getClassLoader().getResource("config.properties").getPath()));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public CustomerDao getCustomerDao() {
String clazz = properties.getProperty("CustomerDao");
try {
return (CustomerDao) Class.forName(clazz).newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
//在service层需要这么写
CustomerDao customerDao = CustomerDaoFactory.getCustomerFactory().getCustomerDao();
service和dao层需要解耦,web层与service层也需要解耦,
每个解耦都需要构建一个工厂类。
还有一种很基础的实现方式:
public Object getInstance(String clazz) {
clazz = properties.getProperty(clazz);
try {
return Class.forName(clazz).newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
在service层需要这么写:
CustomerDao customerDao = (CustomerDao) BasicFactory.getBasicFactory().getInstance("CustomDao");
不仅需要将类名变成String参数传进去,还需要强转一下。
所以,就用第一个吧。