目前,我不知道如何在我的代码片段中避免代码气味。我尝试了几种模式(Strategy,Visitor),但它们都没有提供一个干净和可维护的解决方案。以下是我的策略模式代码的示例:
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。
发布于 2020-01-10 16:58:46
这看起来像是Factory Method模式的教科书用例。您可以使用与现在相同的代码(或另一个答案中的Map示例),但将其放在工厂中-然后它是特定于特定用途的,并与使用它的代码解耦。
就像这样。
public class StrategyFactory {
public static Stategy getStrategy(Action action) {
if(action instanceof ActionOne) {
return new StrategyOne();
} else if(action instanceof ActionTwo) {
return new StrategyTwo();
}
}
}然后,就像这样。
Action action = item.getAction();
action.setStrategy(StrategyFactory.getStrategy(action));这里还有另一个示例:https://dzone.com/articles/design-patterns-the-strategy-and-factory-patterns
https://stackoverflow.com/questions/59676031
复制相似问题