では「練習問題2:HTTPステータス分類」を 戦略パターンでリファクタリングした解答例を示します。
元のコード(フォールスルーあり)
switch (statusCode) {
case 200:
case 201:
case 204:
System.out.println("成功レスポンス");
break;
case 400:
case 404:
System.out.println("クライアントエラー");
break;
case 500:
case 503:
System.out.println("サーバーエラー");
break;
default:
System.out.println("未知のステータス");
}
Java👉 成功系・クライアントエラー系・サーバーエラー系をまとめるためにフォールスルーを使っています。
戦略パターンによるリファクタ解答
1. 戦略インターフェース
interface HttpStatusHandler {
void handle(int statusCode);
}
Java2. 具体的な戦略クラス
class SuccessHandler implements HttpStatusHandler {
public void handle(int statusCode) {
System.out.println("成功レスポンス: " + statusCode);
}
}
class ClientErrorHandler implements HttpStatusHandler {
public void handle(int statusCode) {
System.out.println("クライアントエラー: " + statusCode);
}
}
class ServerErrorHandler implements HttpStatusHandler {
public void handle(int statusCode) {
System.out.println("サーバーエラー: " + statusCode);
}
}
Java3. コンテキスト(戦略選択)
import java.util.HashMap;
import java.util.Map;
class HttpStatusContext {
private static final Map<Integer, HttpStatusHandler> handlers = new HashMap<>();
static {
// 成功系
handlers.put(200, new SuccessHandler());
handlers.put(201, new SuccessHandler());
handlers.put(204, new SuccessHandler());
// クライアントエラー系
handlers.put(400, new ClientErrorHandler());
handlers.put(404, new ClientErrorHandler());
// サーバーエラー系
handlers.put(500, new ServerErrorHandler());
handlers.put(503, new ServerErrorHandler());
}
public static void execute(int statusCode) {
HttpStatusHandler handler = handlers.get(statusCode);
if (handler != null) {
handler.handle(statusCode);
} else {
System.out.println("未知のステータス: " + statusCode);
}
}
}
Java4. 利用側
public class Main {
public static void main(String[] args) {
HttpStatusContext.execute(200); // 成功レスポンス: 200
HttpStatusContext.execute(404); // クライアントエラー: 404
HttpStatusContext.execute(503); // サーバーエラー: 503
HttpStatusContext.execute(999); // 未知のステータス: 999
}
}
Java解説
- switch文のフォールスルーを排除
→ Mapに「ステータスコード」と「戦略クラス」を紐付けることで安全に分類。 - メリット
- フォールスルーの危険がなくなる。
- 新しいステータスコードを追加する場合はMapに登録するだけ。
- 各戦略クラスを単体テスト可能。
- デメリット
- クラス数が増えるので小規模な処理には冗長。
- ただし業務コードでは「責務分離」「拡張性」が重要なので有効。
まとめ
- フォールスルーを使わずに「複数条件をまとめる」には、戦略パターン+Map登録が有効。
- HTTPステータス分類のような「グループ化された条件分岐」に適している。


