当前位置:   article > 正文

开始慢慢学习这本书了。。Python编程实战:运用设计模式、并发和程序库创建高质量程序...

python 编程实战:运用设计模式、并 发和程序库创建高质量程序 微盘

没办法,不到设计模式,算法组合这些,在写大一点程序的时候,总是力不从心。。。:(

一开始可能要花很多时间来慢慢理解吧,,这毕竟和《大话设计模式》用的C#语言有点不太一样。。。

书上代码是3版本的,有些库的用法不一样,还要改回2.7的才可以测试。。:(

  1. #!/usr/bin/env python3
  2. # Copyright 漏 2012-13 Qtrac Ltd. All rights reserved.
  3. # This program or module is free software: you can redistribute it
  4. # and/or modify it under the terms of the GNU General Public License as
  5. # published by the Free Software Foundation, either version 3 of the
  6. # License, or (at your option) any later version. It is provided for
  7. # educational purposes and is distributed in the hope that it will be
  8. # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. # General Public License for more details.
  11. import os
  12. import sys
  13. import tempfile
  14. def main():
  15. if len(sys.argv) > 1 and sys.argv[1] == "-P": # For regression testing
  16. create_diagram(DiagramFactory()).save(sys.stdout)
  17. create_diagram(SvgDiagramFactory()).save(sys.stdout)
  18. return
  19. textFilename = os.path.join(tempfile.gettempdir(), "diagram.txt")
  20. svgFilename = os.path.join(tempfile.gettempdir(), "diagram.svg")
  21. txtDiagram = create_diagram(DiagramFactory())
  22. txtDiagram.save(textFilename)
  23. print("wrote", textFilename)
  24. svgDiagram = create_diagram(SvgDiagramFactory())
  25. svgDiagram.save(svgFilename)
  26. print("wrote", svgFilename)
  27. def create_diagram(factory):
  28. diagram = factory.make_diagram(30, 7)
  29. rectangle = factory.make_rectangle(4, 1, 22, 5, "yellow")
  30. text = factory.make_text(7, 3, "Abstract Factory")
  31. diagram.add(rectangle)
  32. diagram.add(text)
  33. return diagram
  34. class DiagramFactory:
  35. def make_diagram(self, width, height):
  36. return Diagram(width, height)
  37. def make_rectangle(self, x, y, width, height, fill="white",
  38. stroke="black"):
  39. return Rectangle(x, y, width, height, fill, stroke)
  40. def make_text(self, x, y, text, fontsize=12):
  41. return Text(x, y, text, fontsize)
  42. class SvgDiagramFactory(DiagramFactory):
  43. def make_diagram(self, width, height):
  44. return SvgDiagram(width, height)
  45. def make_rectangle(self, x, y, width, height, fill="white",
  46. stroke="black"):
  47. return SvgRectangle(x, y, width, height, fill, stroke)
  48. def make_text(self, x, y, text, fontsize=12):
  49. return SvgText(x, y, text, fontsize)
  50. BLANK = " "
  51. CORNER = "+"
  52. HORIZONTAL = "-"
  53. VERTICAL = "|"
  54. class Diagram:
  55. def __init__(self, width, height):
  56. self.width = width
  57. self.height = height
  58. self.diagram = _create_rectangle(self.width, self.height, BLANK)
  59. def add(self, component):
  60. for y, row in enumerate(component.rows):
  61. for x, char in enumerate(row):
  62. self.diagram[y + component.y][x + component.x] = char
  63. def save(self, filenameOrFile):
  64. file = None if isinstance(filenameOrFile, str) else filenameOrFile
  65. try:
  66. if file is None:
  67. #file = open(filenameOrFile, "w", encoding="utf-8")
  68. file = open(filenameOrFile, "w")
  69. for row in self.diagram:
  70. #print "hahah"
  71. print >>file,"".join(row)
  72. finally:
  73. if isinstance(filenameOrFile, str) and file is not None:
  74. file.close()
  75. def _create_rectangle(width, height, fill):
  76. rows = [[fill for _ in range(width)] for _ in range(height)]
  77. for x in range(1, width - 1):
  78. rows[0][x] = HORIZONTAL
  79. rows[height - 1][x] = HORIZONTAL
  80. for y in range(1, height - 1):
  81. rows[y][0] = VERTICAL
  82. rows[y][width - 1] = VERTICAL
  83. for y, x in ((0, 0), (0, width - 1), (height - 1, 0),
  84. (height - 1, width -1)):
  85. rows[y][x] = CORNER
  86. return rows
  87. class Rectangle:
  88. def __init__(self, x, y, width, height, fill, stroke):
  89. self.x = x
  90. self.y = y
  91. self.rows = _create_rectangle(width, height,
  92. BLANK if fill == "white" else "%")
  93. class Text:
  94. def __init__(self, x, y, text, fontsize):
  95. self.x = x
  96. self.y = y
  97. self.rows = [list(text)]
  98. SVG_START = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  99. <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
  100. "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
  101. <svg xmlns="http://www.w3.org/2000/svg"
  102. xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"
  103. width="{pxwidth}px" height="{pxheight}px">"""
  104. SVG_END = "</svg>\n"
  105. SVG_RECTANGLE = """<rect x="{x}" y="{y}" width="{width}" \
  106. height="{height}" fill="{fill}" stroke="{stroke}"/>"""
  107. SVG_TEXT = """<text x="{x}" y="{y}" text-anchor="left" \
  108. font-family="sans-serif" font-size="{fontsize}">{text}</text>"""
  109. SVG_SCALE = 20
  110. class SvgDiagram:
  111. def __init__(self, width, height):
  112. pxwidth = width * SVG_SCALE
  113. pxheight = height * SVG_SCALE
  114. self.diagram = [SVG_START.format(**locals())]
  115. outline = SvgRectangle(0, 0, width, height, "lightgreen", "black")
  116. self.diagram.append(outline.svg)
  117. def add(self, component):
  118. self.diagram.append(component.svg)
  119. def save(self, filenameOrFile):
  120. file = None if isinstance(filenameOrFile, str) else filenameOrFile
  121. try:
  122. if file is None:
  123. #file = open(filenameOrFile, "w", encoding="utf-8")
  124. file = open(filenameOrFile, "w")
  125. file.write("\n".join(self.diagram))
  126. file.write("\n" + SVG_END)
  127. finally:
  128. if isinstance(filenameOrFile, str) and file is not None:
  129. file.close()
  130. class SvgRectangle:
  131. def __init__(self, x, y, width, height, fill, stroke):
  132. x *= SVG_SCALE
  133. y *= SVG_SCALE
  134. width *= SVG_SCALE
  135. height *= SVG_SCALE
  136. self.svg = SVG_RECTANGLE.format(**locals())
  137. class SvgText:
  138. def __init__(self, x, y, text, fontsize):
  139. x *= SVG_SCALE
  140. y *= SVG_SCALE
  141. fontsize *= SVG_SCALE // 10
  142. self.svg = SVG_TEXT.format(**locals())
  143. if __name__ == "__main__":
  144. main()

  

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/1006206
推荐阅读
相关标签
  

闽ICP备14008679号