查看: 462|回复: 4
打印 上一主题 下一主题

【设计模式玩pyBoard】1.简单工厂模式

[复制链接] qrcode

18

主题

29

帖子

82

积分

注册会员

Rank: 2

积分
82
楼主
跳转到指定楼层
发表于 2016-6-1 09:35 AM | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    简单工厂模式:简单理解就是同意类型的类,每个类实现相同的功能函数,将这些函数统一归纳出来,在执行时根据条件来决定执行的是哪一个类中的功能。
    代码:以pyboard的四个LED为例。
  1. import pyb

  2. class IntensityX:
  3.         def Intensity(self, value):
  4.                 return 0

  5. class IntensityValue(IntensityX):
  6.         def Intensity(self, vaule):
  7.                 return vaule

  8. class IntensityPercent(IntensityX):
  9.         pc = 0
  10.         def __init__(self, percent):
  11.                 self.pc = percent
  12.         def Intensity(self, value):
  13.                 return int(value * self.pc)
  14.                
  15. class IntensityCut(IntensityX):
  16.         top = 0
  17.         cut = 0
  18.         def __init__(self, t, c):
  19.                 self.top = t
  20.                 self.cut = c
  21.         def Intensity(self, value):
  22.                 if (value >= self.top):
  23.                         return value - self.cut
  24.                 else:
  25.                         return value

  26. class IntensityLED:
  27.         def __init__(self, intensityX):
  28.                 self.super = intensityX
  29.         def GetIntensity(self, value):
  30.                 return self.super.Intensity(value)

  31. if __name__ == "__main__":
  32.         Intensity = IntensityLED(IntensityValue())
  33.         pyb.LED(4).intensity(Intensity.GetIntensity(200))
  34.         pyb.delay(1000)
  35.         Intensity = IntensityLED(IntensityPercent(0.1))
  36.         pyb.LED(4).intensity(Intensity.GetIntensity(255))
  37.         pyb.delay(1000)
  38.         Intensity = IntensityLED(IntensityCut(255, 55))
  39.         pyb.LED(4).intensity(Intensity.GetIntensity(255))
复制代码

    写了一大堆代码,其实这个功能用几个if...else...也能实现。确实能实现,而且代码会更少,只不过这里的举例比较简单,而在真正做项目时可能会遇到类似的但是比较复杂的场景,这样就能体现出方便了。
    Python中没有switch,所以这种方式在一定程度上也可以代替。


回复

使用道具 举报

0

主题

101

帖子

26

积分

新手上路

Rank: 1

积分
26
沙发
发表于 2016-6-7 11:14 AM | 只看该作者

不错,感谢楼主的分享,学习了。。。
回复 支持 反对

使用道具 举报

38

主题

120

帖子

145

积分

注册会员

Rank: 2

积分
145
板凳
发表于 2016-6-7 11:31 AM | 只看该作者
yhxc8979797 发表于 2016-6-7 11:14
不错,感谢楼主的分享,学习了。。。

谢谢,互相学习
回复 支持 反对

使用道具 举报

1

主题

80

帖子

5

积分

新手上路

Rank: 1

积分
5
地板
发表于 2016-6-7 12:58 PM | 只看该作者
不错,学习学习
回复 支持 反对

使用道具 举报

45

主题

212

帖子

319

积分

中级会员

Rank: 3Rank: 3

积分
319
5#
发表于 2016-6-7 04:55 PM | 只看该作者
本帖最后由 tjCFeng 于 2016-6-7 16:56 编辑
whoisliang 发表于 2016-6-7 12:58
不错,学习学习

共同学习
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表