package com.muyu.data.processing.strategy;

import com.muyu.common.caffeine.utils.CacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
 * 抽象策略路由
 * @Author: 胡杨
 * @Name: abstractStrategyRouter
 * @Description: 抽象策略路由
 * @CreatedDate: 2024/9/28 上午9:26
 * @FilePath: com.muyu.data.processing.strategy
 */
@Slf4j
@Component
public abstract class abstractStrategyRouter<T,R> {

    protected static CacheUtils cacheUtils = new CacheUtils();

    /**
     * 策略映射器, 指定入参与出参以决定策略处理者
     * @param <T>   策略入参
     * @param <R>   策略出参
     */
    public interface StrategyMapper<T,R>{
        // 通过入参获取对应策略处理方法,使用Map实现
        StrategyHandler<T,R> getHandler(T param);
    }

    /**
     * 选择下级策略
     * @return
     */
    protected abstract StrategyMapper<T,R> registerStrategy();

    /**
     * 默认策略处理者
     */
    @SuppressWarnings("unchecked")
    private StrategyHandler<T,R> defaultStrategyHandler = StrategyHandler.DEFAULT;


    /**
     * 选择策略处理者
     * @param param 入参
     * @return 策略处理结果
     */
    public R applyStrategy(T param) {
        StrategyMapper<T, R> trStrategyMapper = registerStrategy();
        if (trStrategyMapper == null) {
            return defaultStrategyHandler.apply(param);
        }
        final StrategyHandler<T,R> strategyHandler = trStrategyMapper.getHandler(param);
        if (strategyHandler != null) {
            return strategyHandler.apply(param);
        }
        // 使用默认策略处理者
        return defaultStrategyHandler.apply(param);
    }
}
