You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Generics vs Inheritance解决代码重复:多类读取器优化问询

消除ReaderForABC代码重复的可行方案

你当前的核心问题是readX和computeX系列方法存在大量重复逻辑,且受限于遗留系统无法修改A、B、C类的继承/接口实现,以下是两种简洁的优化方案:

方案1:用策略模式统一read方法

通过策略映射替代硬编码的类型判断,既实现单一read方法,又保证扩展性:

步骤1:定义计算策略接口

用函数式接口封装不同类型的compute逻辑:

@FunctionalInterface
private interface ComputeStrategy<T> {
    T compute();
}

步骤2:初始化策略映射

在ReaderForABC的构造方法中,建立类型与对应计算策略的映射:

public class ReaderForABC {
    private final Map<Class<?>, ComputeStrategy<?>> strategyMap;

    public ReaderForABC() {
        strategyMap = new HashMap<>();
        strategyMap.put(A.class, this::computeA);
        strategyMap.put(B.class, this::computeB);
        strategyMap.put(C.class, this::computeC);
    }

    // 原有的computeA、computeB、computeC方法保留
    private static A computeA() { /* ... */ }
    private static B computeB() { /* ... */ }
    private static C computeC() { /* ... */ }
    private static void doLotsOfCommonThings() { /* ... */ }
}

步骤3:实现统一的read方法

通过映射获取对应策略,执行公共逻辑+计算逻辑:

@SuppressWarnings("unchecked")
public <T> T read(Class<T> clazz) {
    doLotsOfCommonThings();
    ComputeStrategy<T> strategy = (ComputeStrategy<T>) strategyMap.get(clazz);
    if (strategy == null) {
        throw new IllegalArgumentException("不支持的类型:" + clazz.getSimpleName());
    }
    return strategy.compute();
}

使用方式

ReaderForABC reader = new ReaderForABC();
A a = reader.read(A.class);
B b = reader.read(B.class);
C c = reader.read(C.class);

这种方式避免了冗长的if-else判断,后续新增类型只需在映射中添加新策略,无需修改read方法,符合开闭原则。

方案2:用模板方法消除computeX的重复

针对computeX及其内部调用的helper函数中的重复逻辑,可抽取公共模板,仅保留差异部分:

步骤1:抽取compute公共模板

将computeA/B/C中的公共逻辑抽成模板方法,差异部分通过函数式接口传入:

private <T> T computeTemplate(Supplier<T> finalComputeStep) {
    // 这里放computeA/B/C的公共代码
    doCommonComputeWork();
    // 执行差异逻辑
    return finalComputeStep.get();
}

private void doCommonComputeWork() {
    // 原computeX中的公共逻辑,比如前置校验、通用数据处理等
}

步骤2:重构computeX方法

用模板方法替代重复代码,仅保留各自的差异逻辑:

private static A computeA() {
    return computeTemplate(() -> {
        // 这里仅保留computeA独有的逻辑,比如调用A的专属helper
        return helperComputeA();
    });
}

private static B computeB() {
    return computeTemplate(() -> {
        return helperComputeB();
    });
}

private static C computeC() {
    return computeTemplate(() -> {
        return helperComputeC();
    });
}

同理,helperCompute系列方法的重复也可以用这种方式处理,逐层抽取公共模板,彻底消除嵌套的重复代码。


内容的提问来源于stack exchange,提问作者KII

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:54:52