gpt4 book ai didi

java - java中如何实现模式匹配,避免instanceof?

转载 作者:行者123 更新时间:2023-12-05 01:01:20 25 4
gpt4 key购买 nike

目前我不知道如何避免我的代码中出现代码异味。我尝试了几种模式(策略、访客),但它们没有提供干净且可维护的解决方案。这是我的策略模式代码示例:

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。

最佳答案

我头顶的两种方式。

public abstract class Action {
public Strategy strategy;
abstract void bar();
}

public class ActionOne extends Action {
void bar() {}
// set strategy here, possibly
}

public class ActionTwo extends Action {
void bar() {}
}

public void doSmth(Item item) {
Action action = item.getAction();
action.strategy.execute(firstParam, secondParam);
}

第二种方式,在你的所有 Action 中都有一个枚举,并通过在你的抽象类构造函数中将它声明为参数来强制它。然后只需使用 switch in 而不是 instanceof

关于java - java中如何实现模式匹配,避免instanceof?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59676031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com