【问题标题】:Which design pattern is most appropriate, if any哪种设计模式最合适(如果有)
【发布时间】:2019-03-08 10:59:45
【问题描述】:

所以,这个代码元素有可能变得非常丑陋。有可能在每个 if 语句以及更多 if/else 语句中向列表中添加多个元素。设计这段代码的最佳模式或方式是什么。我在考虑责任链,但这意味着到处传递列表,这不是最好的,甚至不是构建器模式?有什么想法吗??

    List<String> aList = new ArrayList<>();

    if (something.contains(Effect.HARD)) {
        aList.add("");
    }

    if (something.contains(Effect.REFLECT)) {
        aList.add("");
        aList.add("");
    } else {
        aList.add("no reflect");
    }

    if (something.contains(Effect.OUTLINE)) {
        aList.add("something");
    }

    if (something.contains(Effect.GRADIENT)) {
        aList.add("gradient");
    } else {
        aList.add("no gradient");
    }

【问题讨论】:

  • "...如果是 y"?一个“y”是什么?
  • 不确定如何将其放入模式中。创建了一个模式来处理以相同方式工作的事件/事物/...,但这里似乎并非如此。
  • 至于你的问题,能不能详细说说你的真正问题?这段代码应该解决什么问题?如果我们知道您要解决的实际问题是什么,我们就更容易提出另一个可能更好的解决方案。现在,您的问题是XY problem
  • 您可以使用策略模式来实现您正在检查 Contains 的 switch case 类型的功能,每个 contains 都有可能成为一种策略,使您的代码保持干净和可读。

标签: java design-patterns


【解决方案1】:

使用visitor(链接到维基百科页面)。

这是一些轻松的示例代码:

public interface Visilator
{
  // Process the stuff and, maybe, add an element to the kerplungy list.
  void doStuff(Stuff stuff, List<Kerplungy> kerplungyList);
}

public class Kerplungilator
{
  // Actually create this however you choose.
  @Autowired
  private List<Visilator> visilatorList;

  public List<Kerplungy> processStuffs(final Stuff stuff)
  {
    final List<Kerplungy> returnValue = LinkedList<>(); // ArrayList is for chumps.

    for (final Visilator current : visilatorList)
    {
      current.doStuff(Stuff, returnValue);
    }

    return returnValue;
  }
}

public clss HootVisilator
implements Visilator
{
  public void doStuff(
    @NotNull final Stuff stuff,
    @NotNull final List<Kerplungy> kerplungyList)
  {
    if (stuff.hoot())
    {
      final Kerplungy hootKerplungy = new Kerplungy("hoot");

      kerplungyList.add(hootkerplungy);
    }
    else
    {
      System.out.println("not hoot");
    }
  }
}

【讨论】:

    【解决方案2】:

    通常你会考虑用多态代码替换那些丑陋的条件,但这在这里不会很好用,因为条件 (something.contains(...)) 不是基于对象的类型。您可以将它们变成对象,但这也不是一个优雅的解决方案。可以使用 Builder 和 Visitor,但我非常怀疑您的代码是否更具可读性。

    【讨论】:

      猜你喜欢
      • 2011-02-27
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 2016-01-06
      • 2011-03-18
      相关资源
      最近更新 更多