Skip to content

Generic Design Patterns

Andrzej Kebab edited this page Feb 4, 2024 · 5 revisions

UtilityLibrary.Unity.Runtime.Patterns

Observer<T> Class

The Observer<T> class is a generic observer pattern implementation for Unity, allowing monitoring and reacting to changes in a value of type T. This class is particularly useful for implementing reactive programming patterns in Unity applications.

Properties

Value

  • Type: T
  • Get/Set: The current value being observed. Setting a new value triggers the observer's callback.

Constructors

Observer(T value, UnityAction<T> callback = null)

  • Parameters:
    • value: The initial value of the observer.
    • callback: An optional callback function to be invoked when the value changes.

Methods

Set(T value)

Sets a new value for the observer, triggering the callback if the new value is different from the current one.

Invoke()

Invokes the callback with the current value.

AddListener(UnityAction<T> callback)

Adds a new listener to the observer, registering a callback function to be invoked when the value changes.

RemoveListener(UnityAction<T> callback)

Removes a listener from the observer, unregistering a previously added callback function.

RemoveAllListeners()

Removes all listeners from the observer, clearing all registered callback functions.

Dispose()

Disposes of the observer, removing all listeners and resetting the value to its default.

Unity-specific Implementation

The class includes Unity-specific features:

  • Serialization attributes for Unity Editor (SerializeField).
  • UnityEvent (UnityEvent<T>) for callback handling.
  • Implicit operator for type conversion (public static implicit operator T(Observer<T> observer)).

Usage Example

// Create an Observer with an initial value of 10
Observer<int> myObserver = new Observer<int>(10, HandleValueChange);

// Set a new value, triggering the callback
myObserver.Set(20);

// Access the current value
int currentValue = myObserver.Value;

// Add a listener for future value changes
myObserver.AddListener(HandleValueChange);

// Remove the listener
myObserver.RemoveListener(HandleValueChange);

// Dispose of the observer
myObserver.Dispose();

// Callback function
void HandleValueChange(int newValue)
{
    Debug.Log($"Value changed to: {newValue}");
}

This class provides a flexible and generic way to implement the observer pattern in Unity applications, allowing for reactive responses to changing values.

Singleton<T> Class

The Singleton<T> class is a generic singleton pattern implementation for Unity, ensuring that only one instance of a component of type T exists in the scene. This class provides flexibility in obtaining or creating the singleton instance.

Properties

AutoUnparentOnAwake

  • Type: bool
  • Default: true
  • Get/Set: Controls whether the singleton instance is automatically unparented on awake.

HasInstance

  • Type: bool
  • Get: Indicates whether an instance of the singleton exists.

TryGetInstance

  • Type: T
  • Get: Attempts to get the existing singleton instance, or returns null if none exists.

Instance

  • Type: T
  • Get: Gets or creates the singleton instance of type T.

Methods

Awake()

  • Description: Unity's Awake method. Make sure to call base.Awake() in override if needed.

InitializeSingleton()

  • Description: Initializes the singleton instance, ensuring that only one instance exists in the scene. Also handles auto-unparenting and marking the GameObject as DontDestroyOnLoad.

Unity-specific Implementation

The class includes Unity-specific features:

  • Inheriting from MonoBehaviour.
  • Use of Unity's DontDestroyOnLoad to persist the GameObject across scenes.

Usage Example

public class MySingleton : Singleton<MySingleton>
{
    // Additional properties or methods specific to the singleton instance can be added here

    // Example usage
    void Start()
    {
        MySingleton.Instance.DoSomething();
    }

    void DoSomething()
    {
        // Implementation details
    }
}

This class provides a generic and flexible way to implement the singleton pattern in Unity, ensuring that only one instance of the specified component type exists in the scene. The class also provides options for auto-unparenting and persistence across scene changes.

RegulatorSingleton<T> Class

The RegulatorSingleton<T> class is a generic singleton pattern implementation for Unity, specifically designed to regulate and destroy any older instances of components of type T. This ensures that only the most recently created instance persists.

Properties

HasInstance

  • Type: bool
  • Get: Indicates whether an instance of the singleton exists.

InitializationTime

  • Type: float
  • Get: The time of initialization of the current instance.

Instance

  • Type: T
  • Get: Gets or creates the singleton instance of type T.

Methods

Awake()

  • Description: Unity's Awake method. Make sure to call base.Awake() in override if needed.

InitializeSingleton()

  • Description: Initializes the singleton instance, ensuring only the most recently created instance persists. Destroys any older instances of the same type.

Unity-specific Implementation

The class includes Unity-specific features:

  • Inheriting from MonoBehaviour.
  • Use of Unity's DontDestroyOnLoad to persist the GameObject across scenes.
  • HideFlags to hide and not save the GameObject in the hierarchy.

Usage Example

public class MyRegulatedSingleton : RegulatorSingleton<MyRegulatedSingleton>
{
    // Additional properties or methods specific to the singleton instance can be added here

    // Example usage
    void Start()
    {
        MyRegulatedSingleton.Instance.DoSomething();
    }

    void DoSomething()
    {
        // Implementation details
    }
}

This class provides a generic and regulated way to implement the singleton pattern in Unity. It ensures that only the most recently created instance of the specified component type persists and destroys any older instances on awake. The class also provides options for hiding and not saving the GameObject in the hierarchy.

Clone this wiki locally