目前,我不知道如何避免代码中的代码味道。 我尝试了几种模式(策略,访客),但它们没有提供干净且可维护的解决方案。这是我的策略模式代码示例:
public interface Strategy {
<T> T foo(FirstParam firstParam,SecondParam secondParam);
}
public class StrategyOne implements Strategy {
FirstReturnType foo(FirstParam firstParam,SecondParam secondParam);
}
public class StrategyTwo implements Strategy {
SecondReturnType foo(FirstParam firstParam,SecondParam secondParam);
}
@Setter
public class Context {
private Strategy strategy;
public void execute(FirstParam firstParam,SecondParam secondParam) {
if (strategy != null) {
strategy.fo(firstParam,secondParam);
}
}
}
还有一个对象示例。
public abstract class action {
abstract void bar();
}
public class actionOne extends action {
void bar() {}
}
public class actionTwo extends action {
void bar() {}
}
我想使这段代码更简洁
public class actionExecutor {
private Context context;
private FirstParam firstParam;
private SecondParam secondParam;
public actionExecutor(FirstParam firstParam,SecondParam secondParam) {
this.context = new Context();
this.firstParam = firstParam;
this.secondParam = secondParam;
}
public void doSmth(Item item) {
action action = item.getaction();
if(action instanceof actionOne) {
context.setStrategy(new StrategyOne());
}
if(action instanceof actionTwo) {
context.setStrategy(new StrategyTwo());
}
context.execute(firstParam,secondParam);
}
}
这个想法是对特定的对象类型执行特定的动作。但是我不知道在这种情况下如何避免使用instanceof。