Single case design mode

Time:2022-5-13

Haomai IT technology trading platform
Objectives:
Single case design mode
__ new__ method
Singleton in Python
1. Single case design mode
Design mode:
Design pattern is the summary and refinement of previous work. Generally, the widely circulated design pattern is a mature solution to a specific problem
The purpose of using design patterns is to reuse code, make code easier to be understood by others and ensure code reliability
Single case design mode
Purpose – let the object created by the class have only one instance in the system
The memory address of the object returned by the class name () is the same every time
Application scenario of single case design pattern
Music playback object
Recycle bin object
Printer object
········
2.__ new__ method
When you create an object using the class name (), the Python interpreter calls__ new__ Method to allocate space for the object, and then call__ init__ () method initialization object
__ new__ It is a built-in static method provided by the object base class. It has two main functions
Allocate space for objects in memory
Returns a reference to an object
After the Python interpreter obtains the reference of the object, it passes the reference as the first parameter to the__ init__ method

class MusicPlayer(object):
    def __new__(cls, *args, **kwargs):
        Print ("create object, allocate space")

    def __init__(self):
        Print ("initialization object")

player = MusicPlayer()
print(player)
'''
Operation results:
Create an object and allocate space: it can be seen that when instantiating an object, the new method is called first to open up space for the object
None: because the new method is rewritten, and the new method needs to pass the address of the object to init,
          It was not initialized because it was not rewritten
'''

Rewrite__ new__ The code of the method is very fixed
Be sure to return super()__ new__ (cls)
Otherwise, the Python interpreter will not call the initialization method of the object if it cannot get the reference of the allocated space
Note:__ new__ Is a static method, which needs to actively pass CLS parameters when callingSingle case design mode

class MusicPlayer(object):
    def __new__(cls, *args, **kwargs):
        #When an object is created, the new method is automatically called
        Print ("create object, allocate space")
        #Allocate space for objects
        instance = super().__new__(cls)
        #Returns a reference to an object
        return instance
    def __init__(self):
        Print ("initialization object")

player = MusicPlayer()
print(player)
'''
Operation results:
Create objects and allocate space
Initialize object
<__main__.MusicPlayer object at 0x000001DC63B9FF10>
'''

Singleton – an object created by a class that has only one instance in the system
Define a class attribute with an initial value of none, which is used to record the reference of the singleton object
Override new method
If the class attribute is none, call the parent class method to allocate space and record the result in the class attribute
Returns the object reference recorded in the class propertySingle case design mode

1 # single case design mode
 2 class MusicPlayer(object):
 3 instance = address of none # record object
 4     def __new__(cls, *args, **kwargs):
 5 # judge whether the object is empty. If it is empty, assign an address to it
 6         if cls.instance is None:
 7 # allocate space for objects
 8             cls.instance = super().__new__(cls)
 9 # return the reference of the object
10             return cls.instance
11 # if the part is empty, the address of the first object is returned
12         else:
13             return cls.instance
14     def __init__(self):
15         pass
16 
17 player_1 = MusicPlayer()    #<__main__.MusicPlayer object at 0x00000282C8B7FDF0>
18 print(player_1)
19 
20 player_2 = MusicPlayer()    #<__main__.MusicPlayer object at 0x00000282C8B7FDF0>
21 print(player_2)
Single case design pattern case

Perform initialization action only once
Requirement: let the initialization action be executed only once
terms of settlement
Define a class attribute init_ Flag flag indicates whether initialization has been performed. The initial value is false
stayinitMethod, determine init_ Flag. If it is false, the initialization action will be executed
Then set init_ Flag set to true
In this way, call again__ init__ Method, the initialization action will not be executed

1 # initialization is performed only once
 2 class MusicPlayer(object):
 3 instance = address of none # record object
 4     init_ Flag = false # mark whether initialization action has been performed
 5     def __new__(cls, *args, **kwargs):
 6 # judge whether the object is empty. If it is empty, assign an address to it
 7         if cls.instance is None:
 8 # allocate space for objects
 9             cls.instance = super().__new__(cls)
10 # return the reference of the object
11             return cls.instance
12 # if the part is empty, the address of the first object is returned
13         else:
14             return cls.instance
15     def __init__(self):
16 # judge whether the initialization action has been executed
17         if MusicPlayer.init_flag:
18             return
19 # if it has not been executed, the initialization action is executed
20 print ("initialize player")
21 # modify the tag of class attribute (init_flag)
22         MusicPlayer.init_flag = True
23 
24 player_1 = MusicPlayer()    #<__main__.MusicPlayer object at 0x00000282C8B7FDF0>
25 print(player_1)
26 player_2 = MusicPlayer()    #<__main__.MusicPlayer object at 0x00000282C8B7FDF0>
27 print(player_2)
28 player_3 = MusicPlayer()    #<__main__.MusicPlayer object at 0x00000282C8B7FDF0>
29 print(player_3)
30 '''
31 operation results:
32 initialize player
33 <__main__.MusicPlayer object at 0x0000029ECB252F10>
34 <__main__.MusicPlayer object at 0x0000029ECB252F10>
35 <__main__.MusicPlayer object at 0x0000029ECB252F10>
36 '''
Perform initialization action only once