大话设计模式(Python版)--模板方法模式

重复=易错+难改

#!/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()




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值