通过工厂和反射来实现IOC

简介

我们都知道IOC是通过工厂和反射以及容器来完成对象的创建、获取及存储的,以下代码便是简单的实现方式,通过这个demo可以更好的去理解IOC。

项目的结构如下:

  1. 添加bean.properties配置文件
    properties文件是以key,value形式进行存储的。key值存储变量名,value存储变量类型(类路径)。
accountService=com.gzl.service.impl.AccountServiceImpl
accountDao=com.gzl.dao.impl.AccountDaoImpl
  1. 添加工厂类
package com.gzl.factory;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BeanFactory {
    /**
     * 定义一个Properties对象
     */
    private static Properties props;

    /**
     * 定义一个Map,用于存放我们要创建的对象。我们把它称之为容器
     */
    private static Map<String, Object> beans;

    //使用静态代码块为Properties对象赋值
    static {
        try {
            //实例化对象
            props = new Properties();
            //获取properties文件的流对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(in);
            //实例化容器
            beans = new HashMap<String, Object>();
            //取出配置文件中所有的Key
            Enumeration keys = props.keys();
            //遍历枚举
            while (keys.hasMoreElements()) {
                //取出每个Key
                String key = keys.nextElement().toString();
                //根据key获取value
                String beanPath = props.getProperty(key);
                //反射创建对象
                Object value = Class.forName(beanPath).newInstance();
                //把key和value存入容器中
                beans.put(key, value);
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化properties失败!");
        }
    }

    /**
     * 根据bean的名称获取对象
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return beans.get(beanName);
    }
}

  1. 首先添加dao层接口
package com.gzl.dao;

/**
* 账户的持久层接口
*/
public interface IAccountDao {

   void saveAccount();
}
  1. 添加dao层接口对应的实现类
package com.gzl.dao.impl;

import com.gzl.dao.IAccountDao;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {

    public void saveAccount() {

        System.out.println("保存了账户");
    }
}

  1. 添加service层接口
package com.gzl.service;

/**
* 账户业务层的接口
*/
public interface IAccountService {

   /**
    * 模拟保存账户
    */
   void saveAccount();
}
  1. 添加service层实现类
package com.gzl.service.impl;

import com.gzl.dao.IAccountDao;
import com.gzl.factory.BeanFactory;
import com.gzl.service.IAccountService;

/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {

  private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");

  public void saveAccount() {
      int i = 1;
      accountDao.saveAccount();
      System.out.println(i);
      i++;
  }
}
  1. 添加一个类,然后添加主函数进行测试
package com.gzl;

import com.gzl.factory.BeanFactory;
import com.gzl.service.IAccountService;

/**
* 模拟一个表现层,用于调用业务层
*/
public class Client {

  public static void main(String[] args) {
      //IAccountService as = new AccountServiceImpl();
      for (int i = 0; i < 5; i++) {
          IAccountService as = (IAccountService) BeanFactory.getBean("accountService");
          System.out.println(as);
          as.saveAccount();
      }

  }
}

  1. 运行结果

总结

以上观察结果多次调用一直是一个对象,spring也是如此,他可以在对象创建前设置该对象是单例还是多例,默认是单例,所谓的单例就是容器当中始终存储的只有一个对象的实例,多次使用的情况下都是使用的这一个对象实例!

真实的IOC要比这个复杂的多,还要考虑对象的单例以及多例、以及线程安全等各种问题,这个demo只能大概了解IOC的思路。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

怪 咖@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值