12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- namespace Wayne.Lib.StateEngine.Generic
- {
- /// <summary>
- /// Generic composite state class that has a main object of a generic type.
- /// </summary>
- /// <typeparam name="TMain">Specifies the type of the main object.</typeparam>
- /// <typeparam name="TData">Specifies the type of state data the state uses.</typeparam>
- public abstract class CompositeState<TMain, TData> : CompositeState<TMain>, IStateWithData where TData : StateData
- {
- #region Fields
- private TData data;
- private IStateWithData stateWithData;
- #endregion
- #region Properties
- /// <summary>
- /// Gets the state data for this state.
- /// </summary>
- protected TData Data
- {
- get
- {
- if (data != null) // Do I have my own data?
- return data;
- else // Otherwise, unwind from parent composite states.
- return stateWithData.StateData as TData;
- }
- }
- StateData IStateWithData.StateData
- {
- get { return Data; }
- }
- #endregion
- #region Methods
- internal override void PerformEnter(StateEntry stateEntry, ref Transition transition)
- {
- InitStateData();
- base.PerformEnter(stateEntry, ref transition);
- }
- internal override void PerformExit()
- {
- base.PerformExit();
- using (data) //Dispose without risk for nullref exceptions
- {
- data = null;
- }
- }
- /// <summary>
- /// CreateStateData method should be overridden by those composite states that does not have the same state data
- /// as their parent state.
- /// </summary>
- /// <param name="parentStateData"></param>
- /// <returns></returns>
- protected virtual TData CreateStateData(StateData parentStateData)
- {
- return null;
- }
- private void InitStateData()
- {
- //Create the state data for this composite state.
- //The composite state has the option to return null, if it wants to use a parent composite state's data object.
- var compositeStateWithData = ParentState as IStateWithData;
- if (compositeStateWithData != null)
- data = CreateStateData(compositeStateWithData.StateData); //Create state data before enter method of state gets called.
- else
- data = CreateStateData(null);
- if (data == null)
- {
- if (stateWithData == null)
- {
- stateWithData = StateData.GetParentCompositeStateWithStateData<TData>(this);
- }
- }
- }
- #endregion
- }
- }
|