工厂模式的一个简单实现

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");
    }
}
点赞