Guest User

Untitled

a guest
Sep 21st, 2020
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. from abc import ABC, abstractmethod
  2.  
  3.  
  4. class CarFactory(ABC):
  5.     @abstractmethod
  6.     def create_car(self):
  7.         ...
  8.  
  9.  
  10. class FordFactory(CarFactory):
  11.     def create_car(self):
  12.         pass
  13.  
  14.  
  15. class SingletonMeta(type):
  16.     _instances = {}
  17.  
  18.     def __call__(cls, *args, **kwargs):
  19.         if cls not in cls._instances:
  20.             instance = super().__call__(*args, **kwargs)
  21.             cls._instances[cls] = instance
  22.  
  23.         return cls._instances[cls]
  24.  
  25.  
  26. class FordFactorySingleton(FordFactory, metaclass=SingletonMeta):
  27.     cars_made = 0
  28.  
  29.     def create_car(self):
  30.         self.cars_made += 1
  31.  
  32.  
  33. if __name__ == "__main__":
  34.     ford_factory = FordFactorySingleton()
  35.     ford_factory.create_car()
  36.  
  37.     print(f'ford_factory instance made {ford_factory.cars_made} cars')
  38.  
  39.     ford_factory2 = FordFactorySingleton()
  40.     ford_factory2.create_car()
  41.  
  42.     print(f'ford_factory2 instance made {ford_factory2.cars_made} cars')
  43.  
  44.     print(f'Are they the same objects? {id(ford_factory) == id(ford_factory2)}')
Advertisement
Add Comment
Please, Sign In to add comment