ReisG / Lifor

Organizing time app
1 stars 0 forks source link

User Interface as a singleton #7

Closed ReisG closed 2 years ago

ReisG commented 2 years ago

Don't you think it would be better to turn UserInterface class into singleton. We won't be able to create 2 instances (actually when we will try to make a new one it will return as an existing one)

fresh-ops commented 2 years ago

We can use something like that

class MyBestClass:
   __count = 0

   def __init__(self) -> None:
      MyBestClass.__count += 1

   def __new__(cls):
      if MyBestClass.__count == 0:
         obj = super(MyBestClass, cls).__new__(cls)
         return obj

      raise SyntaxError(f"You can\'t create more then 1 innstance of {MyBestClass.__name__} class")
ReisG commented 2 years ago

I found something interesting about how objects creates:

ReisG commented 2 years ago

I've looked though and understood that it can be implemented like this

class Player:
    ''' It's a singleton class '''
    __slots__ = ('name')
    created_object = None

    def __init__(self, name):
        self.name = name

    def __new__(cls, *args, **kwargs):
        if cls.created_object is None:
            cls.created_object = super().__new__(cls)
            cls.created_object.__init__(*args, **kwargs)
            return cls.created_object
        return cls.created_object

You can try to test it with this code

if __name__ == '__main__':
    a = Player('Max')
    b = Player('Alex')

    print(f"a's name is {a.name}")
    print(f"b's name is {b.name}")
    print(f'a is b == {a is b}')
ReisG commented 2 years ago

But don't forget about encapsulation