享元模式通过共享对象来实现减少内存的使用。
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
对象即可。
上述代码 的输出结果为:
<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)>)>
网友评论