美文网首页
使用枚举类实现策略模式

使用枚举类实现策略模式

作者: 天草二十六_简村人 | 来源:发表于2020-05-07 14:41 被阅读0次

    一、类结构图


    image.png

    二、抽象类ExecutorRouter

    public abstract class ExecutorRouter {
        protected static Logger logger = LoggerFactory.getLogger(ExecutorRouter.class);
    
        /**
         * route address
         *
         * @param addressList
         * @return  ReturnT.content=address
         */
        public abstract ReturnT<String> route(TriggerParam triggerParam, List<String> addressList);
    
    }
    

    三、具体的实现类(略)
    。。。。。。。

    四、枚举

    public enum ExecutorRouteStrategyEnum {
    
        FIRST(I18nUtil.getString("jobconf_route_first"), new ExecutorRouteFirst()),
        LAST(I18nUtil.getString("jobconf_route_last"), new ExecutorRouteLast()),
        ROUND(I18nUtil.getString("jobconf_route_round"), new ExecutorRouteRound()),
        RANDOM(I18nUtil.getString("jobconf_route_random"), new ExecutorRouteRandom()),
        CONSISTENT_HASH(I18nUtil.getString("jobconf_route_consistenthash"), new ExecutorRouteConsistentHash()),
        LEAST_FREQUENTLY_USED(I18nUtil.getString("jobconf_route_lfu"), new ExecutorRouteLFU()),
        LEAST_RECENTLY_USED(I18nUtil.getString("jobconf_route_lru"), new ExecutorRouteLRU()),
        FAILOVER(I18nUtil.getString("jobconf_route_failover"), new ExecutorRouteFailover()),
        BUSYOVER(I18nUtil.getString("jobconf_route_busyover"), new ExecutorRouteBusyover()),
        SHARDING_BROADCAST(I18nUtil.getString("jobconf_route_shard"), null);
    
    // 抽象类ExecutorRouter,具体的实现类直接new(见上),因为是枚举,保证了单实例。
        ExecutorRouteStrategyEnum(String title, ExecutorRouter router) {
            this.title = title;
            this.router = router;
        }
    
        private String title;
        private ExecutorRouter router;
    
        public String getTitle() {
            return title;
        }
        public ExecutorRouter getRouter() {
            return router;
        }
    
    // 未匹配上,则返回默认的策略defaultItem
        public static ExecutorRouteStrategyEnum match(String name, ExecutorRouteStrategyEnum defaultItem){
            if (name != null) {
                for (ExecutorRouteStrategyEnum item: ExecutorRouteStrategyEnum.values()) {
                    if (item.name().equals(name)) {
                        return item;
                    }
                }
            }
            return defaultItem;
        }
    
    }
    

    五、具体的使用示例

            ExecutorRouteStrategyEnum executorRouteStrategyEnum = ExecutorRouteStrategyEnum.match(jobInfo.getExecutorRouteStrategy(), null);    // route strategy
    
    

    相关文章

      网友评论

          本文标题:使用枚举类实现策略模式

          本文链接:https://www.haomeiwen.com/subject/cvhaghtx.html