哪种 java 设计模式适合下述情况?

What java design pattern is appropriate for the situation described below?

我正在开发一个化学包,我有一个 class,其中列出了周期性 table 中的所有元素。理想情况下,元素将是 Java 枚举的一部分。不幸的是,我还需要一个元素作为通配符:每个其他元素都应该 等于 该元素。 Java 不允许覆盖枚举的 equals() 方法,否则我会那样做。谁能针对我刚才描述的情况提出合理的设计模式?

编辑:感谢您的贡献。我确实没有观察到 equals() 要求的传递 属性。

周期性table的元素将分配给图结构上的不同节点(在数学意义上)。给定这个图结构,然后我在原始图中寻找特定子图结构的所有嵌入(子图同构问题)。子图结构的理想 属性 是为某些节点分配了通配符,这样我就可以将这些节点映射到原始图中的任何节点,而不管分配给它的元素是什么。这就是为什么我要寻找一种非传递关系,这样通配符可以等于两个不同的元素,而不暗示元素本身是相等的。我当前的算法使用泛型并调用 equals() 来检查两个节点中的元素是否相等。

正如 mystarrocks 所指出的,您设计的最大问题是它违反了 等于契约 。具体来说,根据 class Object 中的规范,equals 方法应该:

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

(Source)

您的设计会违反传递性 属性。如果钠等于通配符,通配​​符等于钾,则钠必须等于钾。

更好的方法是创建一个辅助 equals 方法,当您想要查看两个元素是否可以 被视为 相等(这不同于相等)时。通配符只是真正等于通配符,但可以认为它等于任何元素。

public enum Element {
  HYDROGEN,
  HELIUM,
  SODIUM,
  //.....
  URANIUM,
  WILD_CARD;

  public boolean consideredEqual(Object other) {
    if (other == null || ! (other instanceof Element)) return false;

    Element e = (Element) other;
    if (this.equals(Element.WILD_CARD) || e.equals(Element.WILD_CARD)) return true;
    return equals(other);
  }
}