6

戦略パターンを実装する Java クラスがいくつかあります。各クラスには、さまざまなタイプの可変数パラメーターがあります。

interface Strategy {
     public data execute(data);
}

class StrategyA implements Strategy {
     public data execute(data);
}

class StrategyB implements Strategy {
      public StrategyB(int paramA, int paramB);
      public data execute(data);
}

class StrategyC implements Strategy {
      public StrategyC(int paramA, String paramB, double paramC);
      public data execute(data);
}

ここで、ユーザーがある種の UI でパラメーターを入力できるようにしたいと考えています。UI は実行時に選択する必要があります。つまり、戦略はそれから独立している必要があります。パラメータ ダイアログはモノリシックであってはならず、戦略や UI (コンソールや Swing など) ごとに動作や外観を変えることができるようにする必要があります。

この問題をどのように解決しますか?

4

3 に答える 3

4

これを行う 1 つの可能性は、Builder デザイン パターンに似たものを使用することです。

すべての戦略タイプに対して、対応するビルダー (1 つ以上) が必要です。ビルダーは、すべての init パラメータをメソッド引数として受け取る通常のビルダーとしては機能しません。代わりに、関連する入力が受信されるまでブロックする必要があります。一部のビルダーは Swing ダイアログを表示して待機し、他のビルダーはコンソールに出力して入力を待機し、他のビルダーはファイルから読み取ることができます。ビルダーはすべての入力を受け取った後、戦略インスタンスを作成して返すことができます。

このようにして、データ取得ロジックを戦略自体から切り離します。もう 1 つの利点は、すべてのビルダーの汎用インターフェースを持つことができるため、特定のビルダーを選択すると、同じコードでそれを操作できることです。

于 2010-04-18T12:06:26.553 に答える
1

この問題の解決策は、主に現在の戦略を決定するものによって異なります。簡単にするために、UI はすべての戦略で同じであると想定しています。

実際には、ビルダー クラスまたはファクトリ メソッドを作成します。この行に沿った何か:

interface StrategyPicker {
    public Strategy getStrategy();
}

// Most likely used in the JFrame it is added to
class StrategyPickerUI extends JPanel implements StrategyPicker {
    // initialize the panel with all the widgets
    // and implement the getStrategy method. the getStrategy
    // method should be called after the input is done in this
    // panel (such as clicking an Ok or Apply button)
}

// You can also make one for the console app
class StrategyPickerSimple implements StrategyPicker {
    // ...
}

本当に凝ったものにしたい場合は、単純なファクトリ クラスを作成して、独自のクラスに作成する行為を削除します。

public class StrategyFactory() {
    public static Strategy createStrategyFromParameters(StrategyParams sp) {
        // creates the Strategy object... doesn't need to be public static
        // and if it isn't, it will help making unit tests easier
    }

    // This nested class could be split up to StrategyAParams, 
    // StrategyBParams, StrategyCParams
    public class StrategyParams {
        data paramA; 
        int paramB_A;
        int paramB_B;
        int paramC_A;
        String paramC_B;
        float paramC_C;
    }
}

// in StrategyPickerUI class
    public getStrategy() {
        StrategyParams sp = new StrategyParams();
        sp.paramB_A = myJTextFieldParamB_A.getText();
           // and so on...
        return StrategyFactory.createStrategyFromParameters(sp);
    }

UI を非モノリシックに保ちたい場合は、責任を独自のオブジェクトに分割します。お役に立てれば。

于 2010-04-18T12:37:18.110 に答える
0

パラメータ クラスに単純なオブジェクト (Numbers、Boolean、Date、String) が含まれている場合は、実行時にインターフェイスの生成を試みることができます。

構成されたオブジェクトとパラメーターのコレクションの UI を生成することがより困難になります。

強力な UI ジェネレーターであるMetawidgetをご覧ください。

于 2010-05-05T16:21:07.647 に答える