0

私はいくつかの仮想的な 2 次元テーブルを持っており、そこからデータをフェッチします。テーブル ID と目的のアイテムの「座標」を受け取り、アイテムを返すメソッドを作成する必要があります。これまでマルチレイヤーswitchesで作ってみたのですが、switchのコードが長すぎて最適解とは思えないので、他に良い方法はないかと考えています。どんな助けでも大歓迎です。

私のコードがどのように見えるかのアイデア:

switch(tableId) {
    case "table 1":
        switch(top) {
            case "whatever":
                switch(side) {
                    // et cetera
    case "table 2":
        // etc
}
4

2 に答える 2

1

ポリモーフィズムを使用します。

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

public interface SearchableTable<T> {
    T getItem(int x, int y);
}

これらのテーブルが管理下にある場合は、このインターフェイスを実装させてください。それ以外の場合は、次のような独自のラッパークラスでテーブルをラップします。

public class SearchableTableWrapper implements SearchableTable<MyItemType> {

    private final Table wrappedThirdPartyTable;

    public SearchableTableWrapper(Table wrappedThirdPartyTable) {
        this.wrappedThirdPartyTable = wrappedThirdPartyTable;
    }

    public MyItemType getItem(int x, int y) {
         ...
    }
}

ここで、テーブルIDとアイテムのインデックスを受け入れる一般的なメソッドを実装する一般的なクラスで、テーブル自体を受け入れ、そのgetItemメソッドを次のように呼び出します。

public class TableUtils {
    public static <T> T getItem(SearchableTable<T> table, int x, int y) {
        return table.getItem(x, y);
    }
}

テーブルの代わりにテーブルIDを取得する必要がある場合は、次のようMapに、テーブルIDから関連するテーブルIDを保持しますSearchableTable

public class TableUtils {

    private static Map<Long, SearchableTable> tableIdToSearchableTable;

    public static <T> T getItem(SearchableTable<T> table, int x, int y) {
        return table.getItem(x, y);
    }
}

このマップには、初期化ブロックまたは静的メソッドSearchableTableを介して、いくつかの方法で実際のマップをロードできます。または、最適な方法で非静的に変更することもできます。staticaddTableTableUtils

ここでの主なことは、ポリモーフィズムを使用することです。

編集

は必要ありませんenum。コメントからのあなたTable1は次のようになります:

public class Table1 implements SearchableTable<String> {
    public String getItem(int x, int y) {
        // use x and y to fetch the item friom the 2-dimensional data structure
    }
}
于 2012-09-10T20:13:08.657 に答える
1

よりオブジェクト指向の方法ですべてを書き直す必要があります.Javaコールドでそれを行う1つのスマートな方法は、いくつかの「調整された」列挙型を使用することです:

enum activity { WHATEVER, SOMETHINGELSE } //Use the same principle as in the enum below ...

enum tables {
  TABLE1(activity.WHATEVER),
  TABLE2(activity.SOMETHINGELSE),

  private activity activity;

  tables(activity activity) {
    this.activity = activity;
  }

  public activity activity() {
   return this.activity;
  }
 }

必要なレベルごとに必要なすべての列挙型を作成した後、次の「トリック」を使用して、長くてマルチレベルの switch 条件ステートメントを回避できます。

String tableId = ...
//Load the table 
tables table = tables.valueOf(tableId);
//Call the related attached activity ...
table.activity();

もちろん、enum 要素には、インターセプトする変数名と同じ名前が必要です (if または switch ステートメントのチェック条件に入れるのと同じ名前)。列挙型の代わりにマップを使用して、別の同様の結果を得ることができます。詳細については、コマンド パターンを参照してください。

于 2012-09-10T19:47:43.217 に答える