工程模式解耦

bean.properties:

accountService=com.wance.service.impl.AccountServiceImpl

AccountServiceImpl.java:

public class AccountServiceImpl implements AccountService {

    @Override
    public void saveAccount() {
        System.out.println("!!");
    }
}

BeanFactory.java:

/**
 * 一个创建Bean对象的工JBean:在计算机英语中,有可重用组件的含义。
 * JavaBean:用java语言编写的可:用组件。
 * javabean>实体类
 * 它就是创建我们的service和dao对象的。
 * 第一个:需要一个配置文件来配置我们的service和dao配置的内容:唯一标识=全限定类名(key=value)
 * 第二个:通过读取配置文件中配置的内容,反射创建对象我的配置文件可以是xmL也可以是properties
 */
public class BeanFactory {
    //定义一个Properties对象
    private static Properties properties;
    //定义一个map,用于存放我们要创建的对象,我们把它称之为容器
    private static Map<String,Object> beans;
    //使用静态代码块为properties对象赋值
    static {
        try {
            //实例化对象
            properties=new Properties();
            //获取properties文件的流对象
            InputStream inputStream=BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            System.out.println(inputStream);
            properties.load(inputStream);
            //实例化容器
            beans=new HashMap<>();
            //取出配置文件中的所有的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) {
           throw new ExceptionInInitializerError("初始化失败");
        }
    }

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

测试类:

public class AccountServiceImplTest {

    @Test
    public void saveAccount() {
        //工程模式解耦
        for (int i=0;i<5;i++){
            AccountService accountService=(AccountService) BeanFactory.getBean("accountService");
            System.out.println(accountService);
            accountService.saveAccount();
        }


    }


结果:

com.wance.service.impl.AccountServiceImpl@64a294a6
!!
com.wance.service.impl.AccountServiceImpl@64a294a6
!!
com.wance.service.impl.AccountServiceImpl@64a294a6
!!
com.wance.service.impl.AccountServiceImpl@64a294a6
!!
com.wance.service.impl.AccountServiceImpl@64a294a6
!!

结果是单例模式,代码运行效率大大提高

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

java后端指南

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

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

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

打赏作者

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

抵扣说明:

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

余额充值