Singleton Design Pattern Flashcards
Singleton Design Pattern
Description:
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is commonly used when you want to have exactly one instance of a class that controls access to a resource, manages a shared state, or performs some centralized actions.
Common Man Explanation:
Imagine you have a class in your game that manages the player’s inventory. Using the Singleton pattern ensures there is only one instance of this InventoryManager throughout the game. Any part of your game that needs to access or modify the player’s inventory can do so through this single instance, ensuring consistency and avoiding the overhead of multiple instances.
When to Use:
Resource Management: When you want to manage a shared resource, such as a game manager, audio manager, or input manager.
Global State: When you need to maintain a global state across the application, such as user preferences or game settings.
Logging/Service Access: When you need a single point of access to a logging system or a network service.
How would you create a Singleton pattern in Unity?
public class GameManager : MonoBehaviour
{
public static GameManager instance;
void Awake() { if (instance == null) { instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } }