State Factory

Purpose

The State Factory addresses the need for efficient and flexible management of finite state machine (FSM) state instances within media playback. Specifically, it solves two problems:

  1. Instance Reuse: Avoids creating multiple instances of the same FSM state by caching singleton instances. This reduces memory overhead and ensures consistent state behavior.

  2. Customization Support: Enables substitution of default FSM state implementations with custom subclasses. This allows developers to override or extend core state behaviors without modifying the FSM core or other subtopics.

By centralizing state creation and caching, the State Factory simplifies FSM state management and promotes modular extensibility for playback state transitions.

Functionality

The State Factory acts as a centralized creator and cache for all FSM state instances used by the playback FSM. Its key workflows and capabilities include:

Key Methods

Example Snippet

public State createState(@NonNull Class classType) {
    Class finalClassType = convertToCustomClass(classType);
    if (finalClassType == null) finalClassType = classType;

    State buildState = getCacheInstance(finalClassType);
    if (buildState == null) {
        Constructor<?> ctor = finalClassType.getConstructor();
        buildState = (State) ctor.newInstance();
        setCacheInstance(finalClassType, buildState);
    }
    return buildState;
}

This snippet shows how the factory creates or retrieves a singleton instance of the requested state or its custom override.

Integration

The State Factory integrates tightly with the parent topic—Finite State Machine Playback—by acting as the authoritative source for all FSM state instances. Its singleton caching mechanism ensures that the FSM player uses consistent state objects across playback sessions, improving performance and reliability.

It complements other subtopics by:

Overall, the State Factory is a foundational utility that underpins the FSM's modular, extensible design by unifying state instantiation and lifecycle management.

State Creation Flowchart

flowchart TD
    A[Request State Instance] --> B{Is there a custom override?}
    B -->|Yes| C[Use Custom State Class]
    B -->|No| D[Use Default State Class]
    C --> E{Is instance cached?}
    D --> E
    E -->|Yes| F[Return Cached Instance]
    E -->|No| G[Create Instance via Reflection]
    G --> H[Cache Instance]
    H --> F

This flowchart visualizes the process of creating or retrieving FSM state instances in the State Factory. It highlights the decision points for custom overrides and caching to ensure efficient, flexible state management.