您的位置:首页 > 编程语言 > Python开发

模板方法模式Python版--考题抄错会做也白搭

2015-03-09 16:49 375 查看
重复=易错+难改

class TestPaperA
def TestQuestion1(self):
print "Test question 1"
print "Answer: b"
def TestQuestion2(self):
print "Test question 2"
print "Answer: a"
def TestQuestion3(self):
print "Test question 3"
print "Answer: c"

class TestPaperA
def TestQuestion1(self):
print "Test question 1"
print "Answer: d"
def TestQuestion2(self):
print "Test question 2"
print "Answer: b"
def TestQuestion3(self):
print "Test question 3"
print "Answer: a"

if __name__ == "__main__":
print "Student A's test paper: "
studentA = TestPaperA()
studentA.TestQuestion1()
studentA.TestQuestion2()
studentA.TestQuestion3()
studentB = TestPaperB()
studentB.TestQuestion1()
studentB.TestQuestion2()
studentB.TestQuestion3()


提炼代码

class TestPaper:
def TestQuestion1(self):
print "Test question 1"
def TestQuestion2(self):
print "Test question 2"
def TestQuestion3(self):
print "Test question 3"

class TestPaperA(TestPaper):
def TestQuestion1(self):
TestPaper.TestQuestion1()
print "Answer: b"
def TestQuestion2(self):
TestPaper.TestQuestion2()
print "Answer: a"
def TestQuestion3(self):
TestPaper.TestQuestion3()
print "Answer: c"

class TestPaperB(TestPaper):
def TestQuestion1(self):
TestPaper.TestQuestion1()
print "Answer: d"
def TestQuestion2(self):
TestPaper.TestQuestion2()
print "Answer: b"
def TestQuestion3(self):
TestPaper.TestQuestion3()
print "Answer: a"
客户端代码同上

改动一下,增加answer

class TestPaper:
def TestQuestion1(self):
print "Test question 1"
print "Answer: ",self.Answer1()
def TestQuestion2(self):
print "Test question 2"
print "Answer: ",self.Answer2()
def TestQuestion3(self):
print "Test question 3"
print "Answer: ",self.Answer3()
def Answer1(self)
pass
def Answer2(self)
pass
def Answer3(self)
pass

class TestPaperA(TestPaper):
def Answer1(self)
return "b"
def Answer2(self)
return "a"
def Answer3(self)
return "c"

class TestPaperB(TestPaper):
def Answer1(self)
return "d"
def Answer2(self)
return "b"
def Answer3(self)
return "a"
模板方法模式

class AbstractClass:
def PrimitiveOperation1(self):
pass
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"

if __name__ =="__main__":
c = ConcreteClassA()
c.TemplateMethod()
c = ConcreteClassB()
c.TemplateMethod()


模板方法模式通过把不变行为搬移到超类,去除子类中的重复代码来体现它的优势。

模板方法模式就是提供了一个很好的代码复用平台。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: