3

非常に単純な変更を加えて、実装で複数回使用するメソッドがあります。どうすれば同じことを繰り返さないようにできますか?

...
    while (!queue.isEmpty()) {
        Element pivot = queue.poll();
        elements.remove(pivot);
        for (Element a : elements) {
            if (areFriends(pivot, a)) {
                db.addRelation(a, pivot);
                queue.add(a);
                elements.remove(a);
            }
        }
    }
...

areFriends 条件を新しい条件 fe areEnemies(Element pivot, Element a) に変更し、コードとデータ構造全体を使い続けたいと考えています。void メソッドを抽出しようとしましたが、この場合、すべての変数 (db、キューなど) を入力として渡す必要があり、アンチパターンのように見えます。この問題を解決する方法はありますか?ありがとうございました!

4

4 に答える 4

3

インターフェイスを作成します。

public interface Relation 
{
    public void execute(Element a, Element b);
}


public class AreFriendsRelation implements Relation 
{
    public void execute(Element a, Element b) 
    {
        // Return the Relation result
    }    
}

public class AreEnemiesRelation implements Relation 
{
    public void execute(Element a, Element b) 
    {
        // Return the Relation result
    }    
}

Relation オブジェクトをメソッドに渡します。

public void MyMethod(Relation myRelation) {
...
while (!queue.isEmpty()) {
        Element pivot = queue.poll();
        elements.remove(pivot);
        for (Element a : elements) {
            if (myRelation.execute(pivot, a)) {
                db.addRelation(a, pivot);
                queue.add(a);
                elements.remove(a);
            }
        }
    }

...
}
于 2013-03-20T16:27:09.033 に答える
3

次を定義できますinterface

public interface IElementFunction
{
    public boolean execute(Element e1, Element e2);
}

そして、共通関数へのパスの実装 (名前付きまたは匿名のいずれかclass) :interface

private void commonFunction(IElementFunction ief)
{
    while (!queue.isEmpty()) {
        Element pivot = queue.poll();
        elements.remove(pivot);
        for (Element a : elements) {
            if (ief.execute(pivot, a)) {
                db.addRelation(a, pivot);
                queue.add(a);
                elements.remove(a);
            }
        }
    }
于 2013-03-20T16:25:56.080 に答える
0

You can use the Command design pattern. Create an interface with method public void checkElements(Element a, Element b), and create a few instances of that interface. In your method, use the interface's method, and either have your method accept an interface instance as a parameter, or have it as a class member.

于 2013-03-20T16:25:12.560 に答える