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

Jas*_*son 2 java oop design-patterns

我有一个具有自定义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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*n C 5

您的问题是,您正在尝试将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);
}
Run Code Online (Sandbox Code Playgroud)

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)