最初我在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