繁体   English   中英

什么是跟踪班级问题的良好设计模式?

[英]What is a good design pattern for tracking issues in a class?

我有一个具有自定义equals()方法的类。 当我使用此equals方法比较两个对象时,我不仅对它们是否相等感兴趣,而且如果它们不相等,它们之间会有什么不同。 最后,我希望能够找回因不平等情况而产生的差异。

我目前使用日志记录来显示我的对象不相等的地方。 这行得通,但是我有一个新的要求,即能够提取等值检查的实际结果以供以后显示。 我怀疑是否存在用于处理此类情况的面向对象的设计模式。

public class MyClass {
  int x;
  public boolean equals(Object obj) {
    // make sure obj is instance of MyClass
    MyClass that = (MyClass)obj;

    if(this.x != that.x) {
      // issue that I would like to store and reference later, after I call equals
      System.out.println("this.x = " + this.x);
      System.out.println("that.x = " + that.x);
      return false;
    } else {
      // assume equality
      return true
    }
  }
}

在完成某项工作时是否有任何好的设计模式建议,但是辅助对象收集有关该工作完成情况的信息,以后可以检索和显示?

您的问题是您试图将boolean equals(Object) API用于并非旨在用于某些目的的东西。 我认为没有任何设计模式可以让您做到这一点。

相反,您应该这样做:

public class Difference {
    private Object thisObject;
    private Object otherObject;
    String difference;
    ...
}

public interface Differenceable {
    /** Report the differences between 'this' and 'other'. ... **/
    public List<Difference> differences(Object other);
}

然后,在需要“可区分”功能的所有类上实现此功能。 例如:

public class MyClass implements Differenceable {
    int x;
    ...

    public List<Difference> differences(Object obj) {
        List<Difference> diffs = new ArrayList<>();
        if (!(obj instanceof MyClass)) {
             diffs.add(new Difference<>(this, obj, "types differ");
        } else {
             MyClass other = (MyClass) obj;
             if (this.x != other.x) {
                 diffs.add(new Difference<>(this, obj, "field 'x' differs");
             }
             // If fields of 'this' are themselves differenceable, you could
             // recurse and then merge the result lists into 'diffs'.
        }
        return diffs;
    }
}

我不知道为此的特定设计模式。 这项要求的一个问题是,要找出两个不相等的对象之间的所有差异,您将需要在第一个错误结果之后继续进行其他比较(这通常是没有必要的)。

如果这样做,我可能会考虑进行普通的相等性测试,如果不相等,则启动一个线程以确定原因并记录结果,而不是将这种逻辑合并到equals方法本身中。 这可以通过equals方法之外的特殊方法来完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM