简化java_Java泛型太复杂了?如何简化?

本文探讨了在Java中使用泛型与继承实现多步骤处理的设计难题,通过具体实例展示了如何设计灵活且易于维护的系统架构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最初我在codereview上发布了这个问题,但这可能更适合stackoverflow。

我用Java 6编码一个多步骤的过程。假设有3个步骤。

每个都接受相同类型的输入。

我们开始吧。

这是作为输入传递给每个步骤的对象。此对象作为另一类型对象的包装,与某些步骤的共享值一起使用。

请注意,名称被翻译成更通用的域名,英文原版是意大利语。

public class EntityStepInput {

public final T entity;

public boolean modified;

public boolean canceled;

public EntityStepInput(final T entity) {

this.entity = entity;

}

}

这是每个步骤使用的接口。

public interface EntityStep> {

void process(final T stepInput) throws Exception;

}

现在,三个步骤中的两个必须接受

EntityStepInput

其中包含

Entity

或从中派生的任何类型。

public class FirstEntityStep implements EntityStep> {

@Override

public void process(final EntityStepInput extends Entity> stepInput) throws Exception {}

}

public class SecondEntityStep implements EntityStep> {

@Override

public void process(final EntityStepInput extends Entity> stepInput) throws Exception {}

}

最后一步必须接受

实体步骤输入

其中包含派生自

实体

.

public class ThirdEntityStep implements EntityStep> {

@Override

public void process(final EntityStepInput extends DerivedEntity> stepInput) throws Exception {}

}

这种用法相当严格。我有超负荷的方法可以接受不同类型的

实体

下面是一个简化版。

public void workWithEntity(final DerivedEntity entity) throws Exception {

final EntityStepInput stepInput = new EntityStepInput(entity);

stepOne.process(stepInput);

stepTwo.process(stepInput);

stepThree.process(stepInput);

}

你可以看到

DerivedEntity

类型可以使用所有步骤。

public void workWithEntity(final OtherDerivedEntity entity) throws Exception {

final EntityStepInput stepInput = new EntityStepInput(entity);

stepOne.process(stepInput);

stepTwo.process(stepInput);

}

这里还有另一种

实体

不能使用最后一步,这是我想要的。

现在,这已经变得非常复杂的仿制药。我担心在我走后谁会读我的代码,不会理解,迟早会搞得一团糟。

这是可简化的吗?你的方法是什么?尽可能尊重单一责任原则?

编辑。

实体

层次结构如下:

Entity > DerivedEntity

Entity > OtherDerivedEntity

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值