【发布时间】:2020-01-10 05:38:39
【问题描述】:
目前我不知道如何避免我的代码中出现代码异味。 我尝试了几种模式(策略、访问者),但它们没有提供干净且可维护的解决方案。这是我的策略模式代码示例:
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。
【问题讨论】:
-
这个人知道设计模式和泛型,但不足以正确使用它们。当您将泛型划分为
FirstReturnType和SecondReturnType时,使用泛型有什么意义。看看 Strategy Pattern,你的 ActionExecutor 应该是这样的。你应该编程接口而不是类。 -
其实
Action Executor是一个业务逻辑类,不能成为Strategy Pattern的一部分。我使用泛型是因为这些方法有不同的返回类型。 -
也许你可以通过 1) 解释你为什么不喜欢使用 instanceof 来改进你的问题 2) 提到你不能修改 Action 类
-
我会避免使用 instanceof,因为它不是一个可扩展且清晰的解决方案。如果
Action类型的数量增加,我应该添加另一个if (action instanceof NewType),这很混乱。 -
@privalou 你收到一个动作,根据动作是什么,你需要设置上下文。动作本身能够设置上下文是有意义的。
标签: java if-statement design-patterns polymorphism instanceof