1. Template Method mode
To do a problem:
Requirement: There are two students to answer questions and write their own answers
#Encoding=utf-8__author__='[email protected]'classStudenta ():defAnswer1 (self):Print 'topic One: XXXXXX' Print 'my answer is: B' defAnswer2 (self):Print 'topic One: XXXXXX' Print 'my answer is: B'classstudentb ():defAnswer1 (self):Print 'topic One: XXXXXX' Print 'my answer is: C' defAnswer2 (self):Print 'topic One: XXXXXX' Print 'my answer is: D'if __name__=='__main__': Student_a=Studenta () student_a.answer1 () Student_a.answer2 () student_b=studentb () student_b.answer1 () Student_b.answer2 ( )
This writing is sure to repeat too many things, such as writing a topic, such as "My answer is" and so on, if we need to create a lot of studentx class, in case one day need to change the topic, we have to change a lot of things,
So the purpose of the template method mode is that all the repetition of things, that need to write more than two times in a template (can be a parent class, can also be a function)
The implementation of the template method:
#Encoding=utf-8__author__='[email protected]'classStudent ():defAnswer1 (self):Print 'topic One: XXXXXX' Print 'My answer is:%s'%Self.get_answer1 ()defGet_answer1 (self):return 'A' defAnswer2 (self):Print 'topic One: XXXXXX' Print 'My answer is:%s'%Self.get_answer2 ()defGet_answer2 (self):return 'A'classStudenta ():defGet_answer1 (self):return 'B' defGet_answer2 (self):return 'B'classstudentb ():defAnswer1 (self):return 'C' defAnswer2 (self):return 'D'if __name__=='__main__': Student_a=Studenta () student_a.answer1 () Student_a.answer2 () student_b=studentb () student_b.answer1 () Student_b.answer2 ( )
One technique used here is that you can define a common method in the parent class, and then the subclass overrides this method to implement the differentiation between subclasses.
Python design mode-Template method mode