持久层接口:AccountDao
public interface AccountDao {
void saveAccount();
}
持久层接口实现类:
public class AccountDaoImpl implements AccountDao {
public void saveAccount() {
System.out.println("保存了账户");
}
}
业务层接口:AccountService
public interface AccountService {
void saveAccount();
}
业务层 接口实现类:AccountServiceImpl
public class AccountServiceImpl implements AccountService{
private AccountDao accountDao = new AccountDaoImpl();
public void saveAccount() {
accountDao.saveAccount();
}
}
表现层:Client
public class Client {
public static void main(String[] args) {
AccountService service = new AccountServiceImpl();
service.saveAccount();
}
}
三层架构的关系:表现层去调用业务层,业务层去调用持久层
现在出了一个问题就是类与类之间的依赖性太强
以上两个分析中可以看出,如果使用new创建实例,那么删了实现类以后就会报错编译期错误,这不是我们想要的,耦合性太强,想要编译期不报错,而是运行期报错,怎么解决?
这个工厂类用于创建service和dao的对象的:
第一步:需要一个配置文件配置我们的service和dao
第二步:通过读取配置文件中配置的内容,反射创建对象
//创建Bean对象的工厂
public class BeanFactory {
private static Properties properties;
static{
properties = new Properties();
try {
properties = new Properties();
InputStream inputStream =
BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//根据Bean的名称获取Bean对象
public static Object getBean(String beanName){
Object bean = null;
try {
String beanPath = properties.getProperty(beanName);
bean = Class.forName(beanPath).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return bean;
}
}
现在重新改进表现层和持久层的实现类:
AccountServiceImpl :
public class AccountServiceImpl implements AccountService{
//private AccountDao accountDao = new AccountDaoImpl();
private AccountDao accountDao =
(AccountDao) BeanFactory.getBean("accountDao");
public void saveAccount() {
accountDao.saveAccount();
}
}
Client:
public class Client {
public static void main(String[] args) {
//AccountService service = new AccountServiceImpl();
AccountService service =
(AccountService) BeanFactory.getBean("accountService");
service.saveAccount();
}
}
这样改进之后就不用new对象了,从而减少了类之间的依赖性。
但是可以看出创建的实例不是同一个,如何改成单例模式呢?
public class BeanFactory {
private static Properties properties;
//定义一个Map,用于存放我们创建的对象,把他称为容器
private static Map<String,Object> beans;
static{
properties = new Properties();
try {
properties = new Properties();
InputStream inputStream =
BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
properties.load(inputStream);
//实例化容器
beans = new HashMap<String,Object>();
//取出配置文件中所有的key
Enumeration keys = properties.keys();
//遍历枚举
while (keys.hasMoreElements()){
//获取每个key
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = properties.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value放入容器中
beans.put(key,value);
}
} catch (Exception e) {
new ExceptionInInitializerError("初始化Properties失败。。。");
}
}
//根据Bean的名称获取Bean对象
public static Object getBean(String beanName){
return beans.get(beanName);
}
}