我有一个具有自定义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 方法之外的特殊方法完成。