クラスでの問題を追跡するための優れたデザインパターンとは何ですか?

ジェイソン:

私は、カスタムのequals()メソッドを持つクラスを持っています。私は、これはequalsメソッドを使用して2つのオブジェクトを比較すると、私は彼らが等しいかどうかに興味を持っていないだけで、彼らが等しくない場合、どのようなことはそれらについて異なっていました。最後に、私は不平等な状況から生じる差異を取得することができるようにしたいです。

私は現在、私のオブジェクトが等しくないディスプレイへのロギングを使用します。この作品は、私は対等の実際の結果は、後で表示するためにチェックを抽出することができるという新しい要件があります。私は、この種の状況を処理するためのオブジェクト指向のデザインパターンがあると思います。

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
    }
  }
}

作品のいくつかの並べ替えが行われている任意の良いデザインパターンの提案はありますが、二次オブジェクトは、後で検索して表示することができるという作業が行われていたどれだけの情報を収集しますか?

スティーブンC:

あなたの問題は、あなたが使用しようとしているということです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);
}

そして、あなたは「differenceable」の機能を必要とするすべてのクラスのためにこれを実装します。例えば:

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;
    }
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=118206&siteId=1