zoukankan      html  css  js  c++  java
  • 模板模式-Python

    这篇文章完全摘录自别人,等后续,基于自己在项目中的应用,再重新写一下。

    模板方法模式(Template Method Pattern):定义一个操作中的算法骨架,将一些步骤延迟至子类中.模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

    demo

    下面是一个模板方法模式的一个demo:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    __author__ = 'Andy'
    """
    大话设计模式
    设计模式——模板方法模式
    模板方法模式(Template Method Pattern):定义一个操作中的算法骨架,将一些步骤延迟至子类中.模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤
    使用场景:当不变和可变的行为在方法的子类实现中混合在一起时,不变的行为就会在子类中重复出现,用模板方法模式把这些不变的行为搬到单一的地方,帮助子类摆脱重复不变的行为纠缠
    """
    class NewPaper(object):
      def question1(self):
        print "题目1"
        print self.answer1()
      def question2(self):
        print "题目2"
        print self.answer2()
      def answer1(self):
        return ''
      def answer2(self):
        return ''
    class TestPaperA(NewPaper):
      def answer1(self):
        return '答案A1'
      def answer2(self):
        return '答案A2'
    class TestPaperB(NewPaper):
      def answer1(self):
        return '答案B1'
      def answer2(self):
        return '答案B2'
    if __name__ == '__main__':
      test1 = TestPaperA()
      test2 = TestPaperB()
      print "试卷A"
      test1.question1()
      test1.question2()
      print "试卷B"
      test2.question1()
      test2.question2()
    

    运行结果如下:

    试卷A
    题目1
    答案A1
    题目2
    答案A2
    试卷B
    题目1
    答案B1
    题目2
    答案B2
    

    应用的注意点

    不能用私有方法,作为模板的子方法。因为继承关系,子类无法改写这个方法

  • 相关阅读:
    [pyqt4]mark
    EPC摘抄
    sockaddr struct 类型重定义
    linux编译警告 will be initialized after
    cout如何输出十六进制
    strcpy unsigned char
    c语言格式控制符
    c++字节数组转换为整型
    C++如何判断大小端
    C++中关于位域的概念
  • 原文地址:https://www.cnblogs.com/meiguhuaxian/p/13052172.html
Copyright © 2011-2022 走看看