工場出荷時のパターンの単純な実装

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

おすすめ

転載: www.cnblogs.com/imisty/p/11227983.html