[Python] Advice on Mixture of Singleton and State Design Pattern in Python

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    in pygame, i'm making a game and as far as i know, nobody creates two instances of a game (justifies Singleton), and my game has different states like "start menu", "game over", "playing" (Justifies State Design Pattern)

    at First i wanted to force the States to be Singleton but i realized i might add states later down the road that need different variables, so this came to my mind:

    class GameState(ABC):

    @abstractmethod
    def exit(self):
    pass


    and this is my GameMeta

    class GameMeta(type):
    _instances = {}

    def __call__(cls):
    if cls not in cls._instances:
    instance = super().__call__()
    cls._instances[cls] = instance
    return cls._instances[cls]


    , i have

    class StartMenu(GameState):
    def exit(self):
    pass


    as a game state, i also have "GameOver" and "Playing" classes similar to "StartMenu", and in my main.py i have Game, it starts the game instance:

    class Game(metaclass=GameMeta):
    def __init__(self):
    self.current_state: GameState = StartMenu()
    self.screen = None


    , is there any sign of bad practice? i'm mixing Singleton and State Pattern, Any Mistakes? or Violation of Design Pattern or Principle? is this a bad idea altogether?

    Continue reading...

Compartilhe esta Página