Singleton pattern: a design pattern. I.e., a class can generate a control target
single mode widely used embodiment, such as music player, video, printer, etc.
Standard wording Singleton pattern
even need to write a single case when the contents of the User class and paste past
1 class User: 2 3 __instance = None 4 def __new__(cls, *args, **kwargs): 5 if cls.__instance is None: 6 cls.__instance = super().__new__(cls) 7 return cls.__instance 8 9 10 u1 = User() 11 u2 = User() 12 print(id(u1)) 13 print(id(u2))
Case:
Office printer
requirements:
a printer to serve everyone in an office to complete their print job
analysis:
Create three categories
1. Printer: 1) add the task to the task queue to be printed in print; 2) completion of printing operation
2. manager: the task to be added to the printer to print
3. employees: Adds the task you want to print to the printer
1 class Printer: 2 __instance = None 3 __pr_list = [] 4 def __new__(cls, *args, **kwargs): 5 if cls.__instance is None: 6 cls.__instance = super().__new__(cls) 7 return cls.__instance 8 9 @staticmethod 10 def add_task(pr_info): 11 Printer.__pr_list.append(pr_info) 12 # Printer.to_print () # wrong! Each time the task will be added before the table of contents in both print and then again 13 14 @staticmethod 15 DEF to_print (): 16 Print (Printer. __Pr_list ) 17 18 19 class Manager: 20 @staticmethod 21 DEF use_printer (Printer, info): 22 is printer.add_task (info) 23 is 24 25 class Stuff: 26 is @staticmethod 27 DEF use_printer (Printer, info): 28 printer.add_task (info) 29 30 31 is= Printer Printer () 32 33 is Manager = Manager () 34 is manager.use_printer (Printer, " manager print " ) 35 36 Stuff = Stuff () 37 [ stuff.use_printer (Printer, " employee print " ) 38 is 39 printer.to_print ()