码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-08-04 21:43:15      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:dict   http   mat   模式   format   counter   name   count   分享   

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

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

学习一下,

有个印象。

技术分享图片

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设计模式》学习结构型之享元模式

标签:dict   http   mat   模式   format   counter   name   count   分享   

原文地址:https://www.cnblogs.com/aguncn/p/9419943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!