Python——工厂设计模式示例

Python——工厂设计模式示例代码如下:


class DiagramFactory:
    @classmethod
    def make_diagram(Class, width, height):
        return Class.Diagram(width, height)

    @classmethod
    def make_rectangle(Class, x, y, width, height, fill='white', stroke='black'):
        return Class.Rectangle(x, y, width, height, fill, stroke)

    @classmethod
    def make_text(Class, x, y, text, fontsize=12):
        return Class.Text(x, y, text, fontsize)


class TextDiagram(DiagramFactory):
    BLANK = " "
    CORNER = "+"
    HORIZONTAL = "-"
    VERTICAL = "|"

    class Text:
        def __init__(self, x, y, text, fontsize):
            self.x = x
            self.y = y
            self.rows = [list(text)]

    class Diagram:
        def __init__(self, width, height):
            self.width = width
            self.height = height
            self.diagram = TextDiagram._create_rectangle(
                self.width, self.height, TextDiagram.BLANK)

        def add(self, component):
            for y, row in enumerate(component.rows):
                for x, char in enumerate(row):
                    self.diagram[y + component.y][x + component.x] = char

        def save(self, fileName):
            fileName = (fileName if isinstance(fileName, str) else None)
            with open(fileName, "w", encoding="utf-8") as f:
                for row in self.diagram:
                    print("".join(row), file=f)

    class Rectangle:
        def __init__(self, x, y, width, height, fill, stroke):
            self.x = x
            self.y = y
            self.rows = TextDiagram._create_rectangle(
                width, height, TextDiagram.BLANK if fill == "white" else "%")

    def _create_rectangle(width, height, fill):
        rows = [[fill for _ in range(width)] for _ in range(height)]
        for x in range(1, width - 1):
            rows[0][x] = TextDiagram.HORIZONTAL
            rows[height - 1][x] = TextDiagram.HORIZONTAL
        for y in range(1, height - 1):
            rows[y][0] = TextDiagram.VERTICAL
            rows[y][width - 1] = TextDiagram.VERTICAL
        for y, x in ((0, 0), (0, width - 1), (height - 1, 0), (height - 1, width - 1)):
            rows[y][x] = TextDiagram.CORNER
        return rows


class SvgDiagram(DiagramFactory):
    SVG_START = """<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" width="{pxwidth}px" height="{pxheight}px">"""

    SVG_END = "</svg>\n"

    SVG_RECTANGLE = """<rect x="{x}" y="{y}" width="{width}" \ height="{height}" fill="{fill}" stroke="{stroke}"/>"""

    SVG_TEXT = """<text x="{x}" y="{y}" text-anchor="left" \ font-family="sans-serif" font-size="{fontsize}">{text}</text>"""

    SVG_SCALE = 20

    class Text:
        def __init__(self, x, y, text, fontsize):
            x *= SvgDiagram.SVG_SCALE
            y *= SvgDiagram.SVG_SCALE
            fontsize *= SvgDiagram.SVG_SCALE // 10
            self.svg = SvgDiagram.SVG_TEXT.format(**locals())

    class Diagram:
        def __init__(self, width, height):
            pxwidth = width * SvgDiagram.SVG_SCALE
            pxheight = height * SvgDiagram.SVG_SCALE
            self.diagram = [SvgDiagram.SVG_START.format(**locals())]
            outline = SvgDiagram.Rectangle(
                0, 0, width, height, "lightgreen", "black")
            self.diagram.append(outline.svg)

        def add(self, component):
            self.diagram.append(component.svg)

        def save(self, filenameOrFile):
            file = (filenameOrFile if isinstance(filenameOrFile, str) else
                    None)
            with open(file, "w", encoding="utf-8") as file:
                file.write("\n".join(self.diagram))
                file.write("\n" + SvgDiagram.SVG_END)

    class Rectangle:
        def __init__(self, x, y, width, height, fill, stroke):
            x *= SvgDiagram.SVG_SCALE
            y *= SvgDiagram.SVG_SCALE
            width *= SvgDiagram.SVG_SCALE
            height *= SvgDiagram.SVG_SCALE
            self.svg = SvgDiagram.SVG_RECTANGLE.format(**locals())


def create_diagram(factory):
    diagram = factory.make_diagram(30, 7)
    rectangle = factory.make_rectangle(4, 1, 22, 5, "yellow")
    text = factory.make_text(7, 3, "Abstract Factory")
    diagram.add(rectangle)
    diagram.add(text)
    return diagram


def main():
    txtDiagram = create_diagram(TextDiagram)
    txtDiagram.save('txtDiagram.txt')
    svgDiagram = create_diagram(SvgDiagram)
    svgDiagram.save('svgDiagram.svg')


if __name__ == "__main__":
    main()

程序运行结果:
《Python——工厂设计模式示例》

    原文作者:Cheney_CHEN_JUN
    原文地址: https://blog.csdn.net/suz_cheney/article/details/80151717
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞