《精通Python设计模式》学习结构型之享元模式

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《精通Python设计模式》学习结构型之享元模式相关的知识,希望对你有一定的参考价值。

这个我日常当中也没有用到过,

真的是游戏行业用得多些?

学习一下,

有个印象。

技术分享图片

import random
from enum import Enum

TreeType = Enum(TreeTye, apple_tree cherry_tree peach_tree)

class Tree:
    pool = dict()

    def __new__(cls, tree_type):
        obj = cls.pool.get(tree_type, None)
        if not obj:
            obj = object.__new__(cls)
            cls.pool[tree_type] = obj
            obj.tree_type = tree_type
        return obj

    def render(self, age, x, y):
        print(render a tree of type {} and age {} at ({}, {})
              .format(self.tree_type, age, x, y))
        


def main():
    rnd = random.Random()
    age_min, age_max = 1, 30
    min_point, max_point = 0, 100
    tree_counter = 0

    for _ in range(10):
        t1 = Tree(TreeType.apple_tree)
        t1.render(rnd.randint(age_min, age_max),
                  rnd.randint(min_point, max_point),
                  rnd.randint(min_point, max_point))
        tree_counter += 1

    for _ in range(3):
        t2 = Tree(TreeType.cherry_tree)
        t2.render(rnd.randint(age_min, age_max),
                  rnd.randint(min_point, max_point),
                  rnd.randint(min_point, max_point))
        tree_counter += 1

    for _ in range(5):
        t3 = Tree(TreeType.peach_tree)
        t3.render(rnd.randint(age_min, age_max),
                  rnd.randint(min_point, max_point),
                  rnd.randint(min_point, max_point))
        tree_counter += 1

if __name__ == __main__:
    main()

技术分享图片

以上是关于《精通Python设计模式》学习结构型之享元模式的主要内容,如果未能解决你的问题,请参考以下文章

Java 设计模式之享元学习与掌握

Java 设计模式之享元学习与掌握

设计模式之享元模式(结构型)

15结构型模式之享元模式

结构型模式之享元模式

结构型模式之享元