重复=易错+难改
#!/usr/bin/env python
class TestPaperA:
def TestQuestion1(self):
print('TestQuestion1')
print('Answer: b')
def TestQuestion2(self):
print('TestQuestion2')
print('Answer: a')
def TestQuestion3(self):
print('TestQuestion3')
print('Answer: c')
class TestPaperB:
def TestQuestion1(self):
print('TestQuestion1')
print('Answer: d')
def TestQuestion2(self):
print('TestQuestion2')
print('Answer: b')
def TestQuestion3(self):
print('TestQuestion3')
print('Answer: a')
def main():
print("Student A's Test paper")
studentA = TestPaperA()
studentA.TestQuestion1()
studentA.TestQuestion2()
studentA.TestQuestion3()
print("Student B's Test paper")
studentB = TestPaperB()
studentB.TestQuestion1()
studentB.TestQuestion2()
studentB.TestQuestion3()
if __name__ == '__main__':
main()
提炼代码
#!/usr/bin/env python
from abc import ABCMeta,abstractmethod
class TestPaper:
__metaclass__ = ABCMeta
def TestQuestion1(self):
print('TestQuestion1')
print('Answer:',self._Answer1())
@abstractmethod
def _Answer1(self):
pass
class TestPaperA(TestPaper):
def _Answer1(self):
return 'b'
class TestPaperB(TestPaper):
def _Answer1(self):
return 'c'
def main():
print("Student A's Test paper")
studentA = TestPaperA()
studentA.TestQuestion1()
print("Student B's Test paper")
studentB = TestPaperB()
studentB.TestQuestion1()
if __name__ == '__main__':
main()
模板方法模式:
#!/usr/bin/env python
from abc import ABCMeta,abstractmethod
class AbstractClass:
__metaclass__ = ABCMeta
@abstractmethod
def PrimitiveOperation1(self):
pass
@abstractmethod
def PrimitiveOperation2(self):
pass
def TemplateMethod(self):
self.PrimitiveOperation1()
self.PrimitiveOperation2()
class ConcreteClassA(AbstractClass):
def PrimitiveOperation1(self):
print('Concrete Class A Operation 1')
def PrimitiveOperation2(self):
print('Concrete Class A Operation 2')
class ConcreteClassB(AbstractClass):
def PrimitiveOperation1(self):
print('Concrete Class B Operation 1')
def PrimitiveOperation2(self):
print('Concrete Class B Operation 2')
def main():
ccA = ConcreteClassA()
ccB = ConcreteClassB()
ccA.TemplateMethod()
ccB.TemplateMethod()
if __name__ == '__main__':
main()