码迷,mamicode.com
首页 > 其他好文 > 详细

工厂模式的一个简单实现

时间:2019-07-22 20:15:42      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:turn   类类型   nts   type   exce   print   简单   for   exception   

1 工厂类

public class TestFactory {

    /**
     *
     */
    private static Map<String, TestInterface> beanMap = ContextUtil.getContext().getBeansOfType(TestInterface.class, false, false);

    public static TestInterface getInstance(String infType) {
        TestInterface curInstance = null;
        for (String beanName : beanMap.keySet()) {
            TestInterface instance = beanMap.get(beanName);
            if (instance.getType() == null)
                throw new RuntimeException("接口实现类类型不可以为空");
            else {
                if (infType.equals(instance.getType())) {
                    curInstance = instance;
                    break;
                }
            }
        }
        return curInstance;
    }
}

2 获取bean类

根据Spring上下文得到某个接口的实现类。

public class ContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ContextUtil.context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }
}

3 需要获取实例的接口类

public interface TestInterface<T> {

    String getType();

    void testFunc(T t);
}

4 TestInterface的一个实现类

public class TestInterfaceImpl implements TestInterface<String> {
    @Override
    public String getType() {
        return "1";
    }

    @Override
    public void testFunc(String s) {
        System.out.println("TestInterfaceImpl -- 01");
    }
}

工厂模式的一个简单实现

标签:turn   类类型   nts   type   exce   print   简单   for   exception   

原文地址:https://www.cnblogs.com/imisty/p/11227983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!