设计模式实战——策略模式

最近本来想优化一个单查为批量查询,然后一顿侧滑之后,反而改了下别人策略的实现,具体的工厂方法实现如下:

@Component
public class TestFactory  implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    public static Map<TestEnum, AbstractConsignTab> strategyMap = Maps.newConcurrentMap();

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

    @Override
    public void afterPropertiesSet(){
        Map<String, AbstractConsignTab> childList = applicationContext.getBeansOfType(AbstractTestTab.class);
        for (Map.Entry<String, AbstractTestTab> abstractConsignTab : childList.entrySet()) {
            strategyMap.put(TestEnumm.getByClassName(abstractConsignTab.getKey()),abstractConsignTab.getValue());
        }
    }
   
public static AbstractTestTab getTestTabStrategy(Integer tab) { TestEnum tabEnum = TestEnum.get(tab); return strategyMap.get(tabEnum); } }

具体枚举实现如下:

public enum TestEnum {
        //tab枚举类
        Tab0(0, "测试0","test0TabStrategy"),
        Tab1(1, "测试1","test1TabStrategy"),
        Tab2(2, "测试2","test2TabStrategy"),
        Tab3(3, "测试3","test3TabStrategy"),
        Tab4(4, "测试4","test4TabStrategy"),
        Tab5(5, "测试5","test5TabStrategy")
        ;
        public int id;
        public String name;
        public String className;

        TabEnum(int id, String name,String className) {
            this.id = id;
            this.name = name;
            this.className=className;
        }

        static Map<Integer, TabEnum> ENUM_MAP = Maps.newHashMap();
        static Map<String, TabEnum> ENUM_CLASS_MAP = Maps.newHashMap();

        static {
            Stream.of(TabEnum.values()).forEach(obj -> {
                ENUM_MAP.put(obj.id, obj);
                ENUM_CLASS_MAP.put(obj.className,obj);
            });
        }

        public static TabEnum get(Integer id) {
            return id == null ? null : ENUM_MAP.get(id);
        }

        public static TabEnum getByClassName(String className) {
            return className == null ? null : ENUM_CLASS_MAP.get(className);
        }

    }

注意下各个实现类,最好指定name,防止类本身重命名,

猜你喜欢

转载自www.cnblogs.com/fbw-gxy/p/11776740.html