In the development process of a project, the logic of some subclasses is roughly the same, but the template pattern reduces code redundancy and reduces coupling.
For example, when realizing a certain form or page startup, the first step needs to load the image resources of the startup interface, the second step needs to load personal information, the third step needs to load personal wallet information, and the fourth step needs to close or hide the previous window (interface). At this point the class can be written as follows:
class LoadNewWindows:
def load(self):
print('Launch screen... ')
self.loadImg()
self.loadUserInfo()
self.loadWalletInfo()
def loadImg(self):
print('Record the picture... ')
def loadUserInfo(self):
print('Load user information... ')
def loadWalletInfo(self):
print('Load wallet info... ')
loadwin=LoadNewWindows()
loadwin.load()
Copy the code
The above class defines a load method that invokes internal methods to implement the process.
Run as follows:
class loadOtherWindows(LoadNewWindows):
def load(self):
print('Launch new screen... ')
self.loadImg()
self.loadUserInfo()
self.loadOtherUserInfo()
def loadOtherUserInfo(self):
print('Load other user information... ')
Copy the code
The above method is a LoadNewWindows subclass, and there is a new method, loadOtherUserInfo, which is used to load other user information. The other process is similar to the parent class, except that the loading wallet is missing, because in this case, the window does not need to load wallet information. The invocation of the process is implemented in load. Finally, two classes are called:
loadwin=LoadNewWindows()
loadwin.load()
print('\n-------------- dividing line ------------\n')
loadOtherWin=loadOtherWindows()
loadOtherWin.load()
Copy the code
The results are as follows:
class LoadNewWindows:
def load(self):
print('Launch screen... ')
self.loadImg()
self.loadUserInfo()
self.loadWalletInfo()
def loadImg(self):
print('Record the picture... ')
def loadUserInfo(self):
print('Load user information... ')
def loadWalletInfo(self):
print('Load wallet info... ')
class loadOtherWindows(LoadNewWindows):
def load(self):
print('Launch new screen... ')
self.loadImg()
self.loadUserInfo()
self.loadOtherUserInfo()
def loadOtherUserInfo(self):
print('Load other user information... ')
loadwin=LoadNewWindows()
loadwin.load()
print('\n-------------- dividing line ------------\n')
loadOtherWin=loadOtherWindows()
loadOtherWin.load()
Copy the code