0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【デザインパターン】 ステートパターン解説(Flutter / Android 実例付き)

0
Last updated at Posted at 2025-09-07

1. パターンの意図

ステート(State)パターン は、
オブジェクトの内部状態に応じて振る舞いを切り替える デザインパターンです。

解決する問題

  • if/else や switch 文で「状態ごとの処理」が乱立してコードが複雑になる
  • 状態が増えるとメンテナンスが困難
  • 状態ごとにクラスを分けて管理したい

ポイント

  • Context:状態を保持する主体
  • State:状態を表すインターフェース
  • ConcreteState:状態ごとの具体的な振る舞いを実装
  • 状態遷移は Context が State を差し替えることで表現

2. UML 図


3. Flutter / Dart 実装例

State インターフェース

abstract class State {
  void handle(Context context);
}

ConcreteState

class ConcreteStateA implements State {
  @override
  void handle(Context context) {
    print("State A: doing work, switching to B");
    context.setState(ConcreteStateB());
  }
}

class ConcreteStateB implements State {
  @override
  void handle(Context context) {
    print("State B: doing work, switching to A");
    context.setState(ConcreteStateA());
  }
}

Context

class Context {
  State _state;

  Context(this._state);

  void setState(State state) {
    _state = state;
  }

  void request() {
    _state.handle(this);
  }
}

利用例

void main() {
  var context = Context(ConcreteStateA());

  context.request(); // State A → B
  context.request(); // State B → A
}

4. Android / Kotlin 実装例

State

interface State {
    fun handle(context: Context)
}

ConcreteState

class ConcreteStateA : State {
    override fun handle(context: Context) {
        println("State A: doing work, switching to B")
        context.setState(ConcreteStateB())
    }
}

class ConcreteStateB : State {
    override fun handle(context: Context) {
        println("State B: doing work, switching to A")
        context.setState(ConcreteStateA())
    }
}

Context

class Context(var state: State) {
    fun setState(state: State) {
        this.state = state
    }

    fun request() {
        state.handle(this)
    }
}

利用例

fun main() {
    val context = Context(ConcreteStateA())

    context.request() // State A → B
    context.request() // State B → A
}

5. 実務ユースケース

Flutter

  • ログイン状態(未ログイン / ログイン済み / セッション切れ)による画面遷移
  • ゲームキャラクターの状態(Idle / Attack / Dead)
  • フォームの入力ステップ管理

Android / Kotlin

  • MediaPlayer の状態(再生 / 一時停止 / 停止)
  • ネットワーク接続状態(接続中 / 接続済み / 切断)
  • UI コンポーネントのライフサイクル管理

6. メリット / デメリット

メリット

  • 状態ごとにクラスを分けることでコードがシンプル
  • 状態遷移が明確になり保守性向上
  • 新しい状態を追加しやすい

デメリット

  • クラス数が増える
  • 状態遷移が複雑すぎると管理が難しい

まとめ

  • State パターンは「内部状態をクラスに分けて自動的に切り替える」設計
  • Flutter/Android では ログイン状態・メディア再生状態・ゲーム状態管理 に多用
  • Strategy = 外部が選ぶ / State = 内部が自動で切り替わる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?