前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >享元模式

享元模式

作者头像
用户2936342
发布2018-08-27 14:23:05
2620
发布2018-08-27 14:23:05
举报
文章被收录于专栏:nummynummy

享元模式通过共享对象来实现减少内存的使用。

代码语言:javascript
复制
import weakref

class Link(object):
    def __init__(self, ref, text, image_path=None):
        self.ref = ref
        if image_path:
            self.image = BrowserImage(image_path)
        else:
            self.image = None
        self.text = text

    def __str__(self):
        if not self.image:
            return "<Link (%s)>" % self.text
        else:
            return "<Link (%s,%s)>" % (self.text, str(self.image))


class BrowserImage(object):
    _resources = weakref.WeakValueDictionary()
    
    def __new__(cls, location):
        image = BrowserImage._resources.get(location, None)
        if not image:
            image = object.__new__(cls)
            BrowserImage._resources[location] = image
            image.__init(location)
        return image

    def __init(self, location):
        self.location = location
        # self.content = load picture into memory

    def __str__(self,):
        return "<BrowserImage(%s)>" % self.location

icon = Link("www.pythonunlocked.com",
            "python unlocked book",
            "http://pythonunlocked.com/media/logo.png")

footer_icon = Link("www.pythonunlocked.com/#bottom",
                   "unlocked series python book",
                   "http://pythonunlocked.com/media/logo.png")

twitter_top_header_icon = Link("www.twitter.com/pythonunlocked",
                               "python unlocked twitter link",
                               "http://pythonunlocked.com/media/logo.png")

print icon
print footer_icon
print twitter_top_header_icon

在上面的例子中,使用Link类来保存链接数据,Browser使用这些链接,可能存在很多链接引用同一张图片,如果每个图片都保存下来,会很占用内存。所以这里使用享元模式,只用创建一个BrowserImage对象即可。

上述代码 的输出结果为:

代码语言:javascript
复制
<Link (python unlocked book,<BrowserImage(http://pythonunlocked.com/media/logo.png)>)>
<Link (unlocked series python book,<BrowserImage(http://pythonunlocked.com/media/logo.png)>)>
<Link (python unlocked twitter link,<BrowserImage(http://pythonunlocked.com/media/logo.png)>)>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.07.07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档