工厂模式

#工厂
package com.spring.base; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class ServiceFactory { private static final String CONF_FILE_NAME="conf.properties"; private static Properties prop; private static Map<String,Object> beanContainer; //静态代码块作用:每次初始化这个类时只加载配置文件 static { try { beanContainer=new HashMap<>(); prop=new Properties(); prop.load(ServiceFactory.class.getClassLoader().getResourceAsStream(CONF_FILE_NAME)); } catch (IOException e) { // e.printStackTrace(); throw new IllegalArgumentException(e); } } public static <T> T getService(Class<T> clazz){ //增加配置文件中key-value的缓存,多次调用同一个key时,不需要再重新使用反射 if (beanContainer.containsKey(clazz.getSimpleName())) { return (T) beanContainer.get(clazz.getSimpleName()); } try { String className = prop.getProperty(clazz.getSimpleName()); Class<?> obj = Class.forName(className); beanContainer.put(clazz.getSimpleName(), obj); return (T) obj.newInstance(); // System.out.println("++++"+className); } catch (Exception e) { throw new IllegalArgumentException(e); } } public static void main(String[] args) { getService(AccountService.class); } }



  
#具体接口和实现类
package com.spring.base; public interface AccountService { void insetAccout(String msg); }

  

package com.spring.base.impl;

import com.spring.base.AccountService;

public class AccountServiceImpl implements AccountService {
    @Override
    public void insetAccout(String msg) {
        System.out.println("=====AccountService==="+msg);;
    }
}

 调用入口: 

package com.spring.base;

public class App {


    public static void main(String[] args) {

        ServiceFactory serviceFactory=new ServiceFactory();

        AccountService accountService1=serviceFactory.getService(AccountService.class);
        accountService1.insetAccout("666");
        AccountService accountservice2=serviceFactory.getService(AccountService.class);
        accountservice2.insetAccout("777");


    }
}

  配置文件:

AccountService=com.spring.base.impl.AccountServiceImpl

 

posted on 2019-09-19 17:14  zz测试笔记  阅读(262)  评论(0编辑  收藏  举报