辞書ウェブサイトからウェブページを解析する単語定義フェッチャーを作成しました。 すべてのWebページがまったく同じHTML構造を持っているわけではないので、大部分のケースをサポートするためにいくつかの解析メソッドを実装する必要がありました。反復的なフォールバックメカニズムを実装するためのデザインパターン
以下は私がこれまで行ってきたことですが、これはかなり醜いコードです。私はNを実装できるように、反復フォールバックメカニズムのいくつかの種類をコーディングするクリーンな方法だろうと思います何
は、メソッドの構文解析注文(パース失敗は次の構文解析をトリガしなければならない、(より適切な用語があるかもしれません) IOExceptionのような例外はプロセスを破壊するはずです)。
public String[] getDefinition(String word) {
String[] returnValue = { "", "" };
returnValue[0] = word;
Document doc = null;
try {
String finalUrl = String.format(_baseUrl, word);
Connection con = Jsoup.connect(finalUrl).userAgent("Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
doc = con.get();
// *** Case 1 (parsing method that works for 80% of the words) ***
String basicFormOfWord = doc.select("DIV.luna-Ent H2.me").first().text().replace("·", "");
String firstPartOfSpeech = doc.select("DIV.luna-Ent SPAN.pg").first().text();
String firstDef = doc.select("DIV.luna-Ent DIV.luna-Ent").first().text();
returnValue[1] = "<b>" + firstPartOfSpeech + "</b><br/>" + firstDef;
returnValue[0] = basicFormOfWord;
} catch (NullPointerException e) {
try {
// *** Case 2 (Alternate parsing method - for poorer results) ***
String basicFormOfWord = doc.select("DIV.results_content p").first().text().replace("·", "");
String firstDef = doc.select("DIV.results_content").first().text().replace(basicFormOfWord, "");
returnValue[1] = firstDef;
returnValue[0] = basicFormOfWord;
} catch (Exception e2) {
e2.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return returnValue;
}
のように、コードを修正し、あなたがのチェーンを考慮することができます責任[パターン](http://www.javacamp.org/designPattern/chains.html) – Renard