最初我在CodeReview上发布了该问题,但这可能更适合StackOverflow。
我正在使用Java 6为多步骤过程进行编码。假设其中有3个步骤。
每个接受相同类型的输入。让我们开始。
这是作为输入传递到每个步骤的对象。除了某些步骤的共享值外,该对象还用作另一种对象的包装。请注意,姓名已翻译成更通用的域名,并且英文使用的是英文原文。
public class EntityStepInput<T extends Entity> {
public final T entity;
public boolean modified;
public boolean canceled;
public EntityStepInput(final T entity) {
this.entity = entity;
}
}
这是每个步骤使用的接口。
public interface EntityStep<T extends EntityStepInput<? extends Entity>> {
void process(final T stepInput) throws Exception;
}
现在,三个步骤中的两个必须接受一个EntityStepInput包含Entity或从其派生的任何类型的。
public class FirstEntityStep implements EntityStep<EntityStepInput<? extends Entity>> {
@Override
public void process(final EntityStepInput<? extends Entity> stepInput) throws Exception {}
}
public class SecondEntityStep implements EntityStep<EntityStepInput<? extends Entity>> {
@Override
public void process(final EntityStepInput<? extends Entity> stepInput) throws Exception {}
}
最后一步必须接受,EntityStepInput其中包含从派生的特定类型Entity。
public class ThirdEntityStep implements EntityStep<EntityStepInput<? extends DerivedEntity>> {
@Override
public void process(final EntityStepInput<? extends DerivedEntity> stepInput) throws Exception {}
}
用法很简单。我有接受不同类型Entitys的重载方法。接下来是一个简化的版本。
public void workWithEntity(final DerivedEntity entity) throws Exception {
final EntityStepInput<DerivedEntity> stepInput = new EntityStepInput<DerivedEntity>(entity);
stepOne.process(stepInput);
stepTwo.process(stepInput);
stepThree.process(stepInput);
}
如您所见,该DerivedEntity类型能够使用所有步骤。
public void workWithEntity(final OtherDerivedEntity entity) throws Exception {
final EntityStepInput<OtherDerivedEntity> stepInput = new EntityStepInput<OtherDerivedEntity>(entity);
stepOne.process(stepInput);
stepTwo.process(stepInput);
}
在这里,另一种类型的Entity不能使用最后一步,这就是我想要的。
现在,使用泛型变得相当复杂。我担心谁会在我走后阅读我的代码,这将不理解,迟早会造成混乱。
这是可简化的吗?在遵循单一责任原则的前提下,您想采取什么方式来尊重他人?
编辑。Entity层次结构如下:
Entity > DerivedEntity
Entity > OtherDerivedEntity
呼如林
相关分类