ポリモーフィズムを使用します。
インターフェイスを作成します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
を介して、いくつかの方法で実際のマップをロードできます。または、最適な方法で非静的に変更することもできます。static
addTable
TableUtils
ここでの主なことは、ポリモーフィズムを使用することです。
編集
は必要ありません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
}
}