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()

程序运行结果:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值