StateFactory.java
Overview
`StateFactory.java` is a core utility class within the Finite State Machine (FSM) Playback module of the media player system. Its primary responsibility is to create, manage, and cache singleton instances of `State` objects used by the FSM to represent various playback states (e.g., playing content, fetching ads, playing ads).
The factory supports:
Singleton caching: Ensures only one instance of each
Statesubclass exists during runtime, optimizing memory and performance.Custom state overrides: Allows replacing default state implementations with user-defined subclasses, enabling flexible extension and customization of playback behavior without modifying the FSM core.
Safe reflection-based instantiation: Dynamically creates state instances via no-argument constructors, abstracting instantiation logic away from consumers.
This class is integral to the FSM playback system, providing a consistent and extensible mechanism to manage the lifecycle of playback states used by the `FsmPlayer`.
Class: StateFactory
Properties
Name | Type | Description |
|---|---|---|
`stateInstance` | `Map` | Cache map storing singleton instances of each `State` subclass. |
`customStateType` | `Map` | Map linking default state classes to custom override classes. |
Methods
public void overrideStateCreation(@NonNull Class subClass)
Registers a custom subclass to override one of the known default FSM `State` classes.
Parameters:
subClass: A subclass of a default BaseState (must extend one of the known default state classes).
Returns: void
Throws:
IllegalStateExceptionifsubClassis not a subclass of any known default state.
Usage:
Call this method once during initialization (before any call tocreateState) to substitute default state implementations with custom ones.Example:
stateFactory.overrideStateCreation(MyCustomMakingAdCallState.class);Implementation Detail:
Internally, this method checks which default state class the provided subclass extends and maps it accordingly incustomStateType.
@NonNull public State createState(@NonNull Class classType)
Creates or returns a cached singleton instance of the specified state class or its custom override.
Parameters:
classType: TheClassobject representing the desiredStatesubclass to instantiate.
Returns:
A singleton instance of the requested
Stateclass.
Throws:
IllegalStateExceptionifclassTypedoes not implement or extendState.
Usage:
This is the primary method to obtain state instances for the FSM player. It ensures reusability and singleton property.Example:
State moviePlayingState = stateFactory.createState(MoviePlayingState.class);Implementation Detail:
Checks if a custom override is registered for the requested class, uses that if present.
Checks the cache for an existing instance.
If none found, uses reflection to instantiate the state via its no-argument constructor.
Caches and returns the instance.
Error Handling:
Catches reflection-related exceptions (NoSuchMethodException,IllegalAccessException, etc.) and prints stack traces but does not throw further.
Private Helper Methods
@Nullable private synchronized State getCacheInstance(@NonNull Class type)
Returns the cached singleton instance of the specified state class, ornullif none exists.private synchronized void setCacheInstance(@NonNull Class type, @NonNull State instance)
Stores the given state instance in the cache.@Nullable private Class convertToCustomClass(@NonNull Class cla)
Returns the custom override class for a given default state class if registered, otherwise returnsnull.
Important Implementation Details and Algorithms
Singleton Caching:
The class maintains aHashMapkeyed byClassobjects to store singleton instances, ensuring that only one instance of each state class exists throughout the application lifecycle.Custom Overrides:
The factory supports dynamic replacement of default FSM states by mapping default classes to custom subclasses. This mapping is checked every time a state instance is requested.Reflection Usage:
Uses Java Reflection API to instantiate states dynamically, requiring that all state classes have a public no-argument constructor.Thread Safety:
Cache access and mutation are synchronized to ensure safe concurrent access.Error Handling:
Reflection exceptions are caught and printed; however, the factory does not propagate these exceptions, potentially returningnullif instantiation fails (though callers expect non-null).
Interaction with Other Parts of the System
FSM Player (
FsmPlayer):
The FSM player relies onStateFactoryto create and retrieve instances ofStateclasses representing playback states. It delegates state transitions and execution to these objects.Concrete State Classes:
The factory creates instances of concrete states such as:FetchCuePointStateMakingPrerollAdCallStateMakingAdCallStateMoviePlayingStateFinishStateReceiveAdStateAdPlayingStateVpaidStateVastAdInteractionSandBoxState
Custom Extensions:
Developers can extend or override these default states by registering custom subclasses with the factory, enhancing or modifying FSM behavior without changing core FSM logic.FSM State Management Workflow:
The factory's caching ensures that the FSM uses consistent state instances, improving performance and reducing object churn during frequent state transitions.
Usage Example
StateFactory stateFactory = new StateFactory();
// Override the MakingAdCallState with a custom implementation before creating any states
stateFactory.overrideStateCreation(MyCustomMakingAdCallState.class);
// Create a state instance (this will return the custom subclass instance)
State makingAdCallState = stateFactory.createState(MakingAdCallState.class);
// Use the state instance within the FSM player
fsmPlayer.setCurrentState(makingAdCallState);
Mermaid Class Diagram
classDiagram
class StateFactory {
- Map<Class, State> stateInstance
- Map<Class, Class> customStateType
+ void overrideStateCreation(Class subClass)
+ State createState(Class classType)
- State getCacheInstance(Class type)
- void setCacheInstance(Class type, State instance)
- Class convertToCustomClass(Class cla)
}
The diagram highlights:
Two private maps:
stateInstance(cache of singleton state instances) andcustomStateType(map for custom overrides).Public methods for overriding state creation and creating states.
Private helper methods managing cache and override mappings.
Summary
`StateFactory.java` is a pivotal utility within the FSM playback system that centralizes state instantiation, caching, and customization. By providing singleton instances of playback states and allowing custom subclass overrides, it enhances performance, modularity, and extensibility of the FSM player. Its design using synchronized caching and reflection-based instantiation makes it flexible and safe for concurrent use in a complex media playback environment.
This factory supports the core FSM playback workflow by ensuring that state objects are consistently managed and easily extendable, thus playing a foundational role in the media player's finite state machine architecture.