单例的工程模式解耦

通过使用工厂模式,实现了表现层——业务层以及业务层——持久层的解耦。例子中的表现层和持久层功能只是简单的模拟一下,不是重点。
第一步:配置文件
创建一个peporties文件

accountService=com.service.impl.AccountServiceImpl
accountDao=com.dao.impl.AccountDaoImpl

第二步:创建Factory

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

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

    //使用静态代码块为Properties对象赋值
    static {
        //实例化对象
        properties = new Properties();
        //获取properties文件的流对象
        InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.Properties");
        try {
            properties.load(in);
            beansMap = new HashMap<String ,Object>();
            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存入容器中
                beansMap.put(key,value);
            }
        } catch (Exception e) {
            throw  new ExceptionInInitializerError("初始化properties失败!");
        }
    }

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

第三步:业务层和持久层
持久层及其实现类

public interface IaccountDao {
    void saveAccount();
}

============================
public class AccountDaoImpl implements IaccountDao {
    @Override
    public void saveAccount() {
        System.out.println("保存成功!");
    }
}

业务层及其实现类

public interface IaccountService {
    void saveAccount();
}

===================================
public class AccountServiceImpl implements IaccountService {
   // IaccountDao dao = new AccountDaoImpl();
    IaccountDao dao = (IaccountDao) BeanFactory.getBean("accountDao");
    @Override
    public void saveAccount() {
        dao.saveAccount();
    }
}

最后简单的测试

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

    }
}

由于在beanFactory中把根据beanPath获取bean对象写在了静态代码块中,所以即使循环获取bean对象,也是只有一个!(单例)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值