State Pattern

April 7, 2026

State = cho phép một object thay đổi hành vi (behavior) của nó khi trạng thái nội bộ (state) thay đổi
State = allows an object to change its behavior when its internal state changes, by delegating behavior to state-specific classes.

Ý tưởng:

  • Thay vì dùng nhiều if-else hoặc switch ❌
  • Tách mỗi trạng thái thành một class riêng ✅

👉 Object chính sẽ:

  • Giữ reference tới current state
  • Delegate hành vi cho state đó State (interface), ConcreteState, Context(Object chính, giữ current state)

Example:

interface State {
    void handle(Context context);
}

class ConcreteStateA implements State {
    public void handle(Context context) {
        System.out.println("State A handling");
        context.setState(new ConcreteStateB());
    }
}

class ConcreteStateB implements State {
    public void handle(Context context) {
        System.out.println("State B handling");
        context.setState(new ConcreteStateA());
    }
}

Context

class Context {
    private State state;

    public Context(State state) {
        this.state = state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public void request() {
        state.handle(this);
    }
}

Usage

public class Main {
    public static void main(String[] args) {
        Context context = new Context(new ConcreteStateA());

        context.request(); // A → switch to B
        context.request(); // B → switch to A
    }
}

Pros

  • Loại bỏ if-else phức tạp
  • Dễ mở rộng (thêm state mới)
  • Code clean

Cons

  • Tăng số lượng class
  • Logic phân tán (khó trace flow)