Java | 「switch → 戦略パターン」リファクタ練習問題

Java Java
スポンサーリンク

では先ほどの 戦略パターンによる switch 置き換え を、UMLクラス図(ASCII版) で視覚化してみます。
これを見ると、各クラスの関係と処理の流れが一目でわかります。


UMLクラス図(ASCII版) — ユーザー権限例

           +----------------+
           |  UserStrategy  |  <<interface>>
           +----------------+
           | + execute()    |
           +----------------+
                   ^
                   |
   ---------------------------------
   |               |               |
+-----------+   +-----------+   +-----------+
| AdminUser |   | NormalUser|   | GuestUser |
+-----------+   +-----------+   +-----------+
| +execute()|   | +execute()|   | +execute()|
+-----------+   +-----------+   +-----------+
       ^
       |
+----------------+
| UserFactory    |
+----------------+
| +getStrategy() |
+----------------+

説明

  • UserStrategy:インターフェース(共通メソッド execute()
  • AdminUser / NormalUser / GuestUser:条件ごとの具体クラス
  • UserFactory:ユーザー種別に応じて戦略オブジェクトを返すファクトリ

UMLクラス図(ASCII版) — 交通信号例

           +----------------------+
           | TrafficLightStrategy |  <<interface>>
           +----------------------+
           | + execute()          |
           +----------------------+
                   ^
                   |
   ---------------------------------
   |               |               |
+---------+     +-----------+    +----------+
| RedLight|     | YellowLight|   | GreenLight|
+---------+     +-----------+    +----------+
| +execute()|   | +execute()|   | +execute()|
+---------+     +-----------+    +----------+
       ^
       |
+-----------------------+
| TrafficLightFactory   |
+-----------------------+
| +getStrategy(light)   |
+-----------------------+

UMLクラス図(ASCII版) — ポイント計算例

           +----------------+
           | PointStrategy  | <<interface>>
           +----------------+
           | +calculate()   |
           +----------------+
                   ^
                   |
   ---------------------------------
   |               |               |
+----------+    +-----------+   +-----------+
| GoldPoint|    | SilverPoint|  | BronzePoint|
+----------+    +-----------+   +-----------+
| +calculate()| | +calculate()| | +calculate()|
+----------+    +-----------+   +-----------+
       ^
       |
+----------------+
| PointFactory   |
+----------------+
| +getStrategy() |
+----------------+

ポイント

  1. インターフェースを中心に、各条件ごとの処理クラスが伸びるイメージ
  2. ファクトリがインスタンス化を一手に引き受ける
  3. メインコードはファクトリから返された戦略オブジェクトに処理を任せるだけ

💡 視覚化すると「switch 文の分岐がオブジェクト構造に置き換わっている」ことが一目で理解できます。

  • フォールスルーも不要
  • 条件追加もクラス追加で対応可能
Java
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました