楼主: 牛尾巴
3122 30

【2016kindle】Learning Python Design Patterns,2e [推广有奖]

11
lionli 发表于 2016-6-18 09:32:59
  1. class HealthCheck:
  2.     _instance = None
  3.     def __new__(cls, *args, **kwargs):
  4.         if not HealthCheck._instance:
  5.             HealthCheck._instance = super(HealthCheck, \
  6.                 cls).__new__(cls, *args, **kwargs)
  7.         return HealthCheck._instance
  8.     def __init__(self):
  9.         self._servers = []
  10.     def addServer(self):
  11.         self._servers.append("Server 1")
  12.         self._servers.append("Server 2")
  13.         self._servers.append("Server 3")
  14.         self._servers.append("Server 4")
  15.     def changeServer(self):
  16.         self._servers.pop()
  17.         self._servers.append("Server 5")

  18. hc1 = HealthCheck()
  19. hc2 = HealthCheck()

  20. hc1.addServer()
  21. print("Schedule health check for servers (1)..")
  22. for i in range(4):
  23.     print("Checking ", hc1._servers[i])

  24. hc2.changeServer()
  25. print("Schedule health check for servers (2)..")
  26. for i in range(4):
  27.     print("Checking ", hc2._servers[i])
  28. The output of the code is as follows:
复制代码

12
bailihongchen 发表于 2016-6-18 09:53:03

The Simple Factory Pattern

  1. from abc import ABCMeta, abstractmethod

  2. class Animal(metaclass = ABCMeta):
  3.     @abstractmethod
  4.     def do_say(self):
  5.         pass

  6. class Dog(Animal):
  7.     def do_say(self):
  8.         print("Bhow Bhow!!")

  9. class Cat(Animal):
  10.     def do_say(self):
  11.         print("Meow Meow!!")


  12. ## forest factory defined
  13. class ForestFactory(object):
  14.     def make_sound(self, object_type):
  15.         return eval(object_type)().do_say()

  16. ## client code
  17. if __name__ == '__main__':
  18.     ff = ForestFactory()
  19.     animal = input("Which animal should make_sound Dog or Cat?")
  20.     ff.make_sound(animal)
复制代码

13
sqy 发表于 2016-6-18 13:49:34
顶!!!!!!!!

14
ekscheng 发表于 2016-6-18 16:08:40

15
mike68097 发表于 2016-6-19 12:44:57

16
zhou_yl 发表于 2016-6-19 19:22:25
好好学习

17
qingxunz 发表于 2016-6-20 05:22:16

18
wyr629 在职认证  发表于 2016-6-20 16:40:57
谢谢分享

19
cfzhang 发表于 2016-6-21 22:43:05
感谢LZ的分享。呵呵

20
raistlinok 发表于 2016-6-22 17:52:10
谢谢分享 不错

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

本版微信群
加好友,备注jltj
拉您入交流群
GMT+8, 2025-12-22 06:45