烽火社区

标题: 【设计模式玩pyBoard】7.模板方法模式 [打印本页]

作者: hongqiao    时间: 2016-6-7 10:12 AM
标题: 【设计模式玩pyBoard】7.模板方法模式
    模板方法模式:先定义一个基础的算法类,在子类中添加操作的步骤。
    代码:

  1. import pyb

  2. class BaseLED:
  3.         def SetTime1(self):
  4.                 pyb.LED(1).on()
  5.                 pyb.delay(self.Set1())
  6.                 pyb.LED(1).off()
  7.                 pyb.delay(self.Set1())
  8.         def SetTime2(self):
  9.                 pyb.LED(2).on()
  10.                 pyb.delay(self.Set2())
  11.                 pyb.LED(2).off()
  12.                 pyb.delay(self.Set1())
  13.         def Set1(self):
  14.                 return 100
  15.         def Set2(self):
  16.                 return 1000
  17.                
  18. class LED1(BaseLED):
  19.         def Set1(self):
  20.                 return 50
  21.         def Set2(self):
  22.                 return 150
  23.                
  24. class LED2(BaseLED):
  25.         def Set1(self):
  26.                 return 1500
  27.         def Set1(self):
  28.                 return 200
  29.        

  30. if __name__ == "__main__":
  31.         l1 = LED1()
  32.         l2 = LED2()
  33.        
  34.         l1.SetTime1()
  35.         l1.SetTime2()
  36.        
  37.         l2.SetTime1()
  38.         l2.SetTime2()
复制代码

        将常用的操作方法归类到父类中,子类只提供不同的参数,完成指定的功能。
        类似考卷,每个考卷的内容相同,考生填写自己的名字,即成为每个考生自己的考卷。
       
       







欢迎光临 烽火社区 (http://bbs.cnecport.com/) Powered by Discuz! X3.2