享元:共享状态、完整键和外部位置
共享可共享的数据,位置及变化状态保留在客户端。
本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。
| 检查项 | 实际结果 | 预期结果 |
|---|---|---|
| 7positions but5unique glyph keys | 5 | 5 |
| repeated l shares object | true | true |
| repeated H shares object | true | true |
| positions remain external | [[0, 0], [6, 0]] | [[0, 0], [6, 0]] |
| shared state frozen | "FrozenInstanceError" | "AttributeError" |
| style is part of key | false | false |
| style bold | true | true |
| style italic | true | true |
| style underline | true | true |
| invalid size | "ValueError" | "ValueError" |
| actual concurrent factory identity | 1 | 1 |
| tree intrinsic shared | true | true |
| tree extrinsic differs | true | true |
| live forest retains weak cached value | 1 | 1 |
| weak cache releases unused value | 0 | 0 |
| actual SVG has7placement nodes | 7 | 7 |
| icon type shared across positions | true | true |
| icon actual file loaded once | 1 | 1 |
| icon different requested size distinct | false | false |
| icon bytes actual | "b'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\"><circle cx=\"12\" cy=\"12\" r=\"10\" fill=\"#2563eb\"/></svg>'" | "b'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\"><circle cx=\"12\" cy=\"12\" r=\"10\" fill=\"#2563eb\"/></svg>'" |
| bad icon size | "ValueError" | "ValueError" |
本章源码与生成文件
查看当前核心代码
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def flyweight(c,out):
factory=GlyphFactory();document=[(factory.get(ch,"Arial",12,"red"if ch=="!"else "black"),(i,0))for i,ch in enumerate("Hello!H")]
c.eq("7positions but5unique glyph keys",len(factory.objects),5)
c.eq("repeated l shares object",document[2][0] is document[3][0],True)
c.eq("repeated H shares object",document[0][0] is document[6][0],True)
c.eq("positions remain external",[document[0][1],document[6][1]],[(0,0),(6,0)])
c.raises("shared state frozen",AttributeError,lambda:setattr(document[0][0],"color","green"))
bold=factory.get("H","Arial",12,"black",bold=True);c.eq("style is part of key",bold is document[0][0],False)
for flag in ("bold","italic","underline"):
item=factory.get("H","Arial",12,"black",**{flag:True});c.eq("style "+flag,getattr(item,flag),True)
c.raises("invalid size",ValueError,lambda:factory.get("A","Arial",0,"black"))
gate=Barrier(8)
def get(_):gate.wait(timeout=10);return factory.get("Z","Arial",12,"black")
with ThreadPoolExecutor(max_workers=8)as pool:items=list(pool.map(get,range(8)))
c.eq("actual concurrent factory identity",len({id(x)for x in items}),1)
import weakref,gc
cache=weakref.WeakValueDictionary()
@dataclass(frozen=True)
class TreeType:
name:str
texture:str
color:str
t=TreeType("pine","owned-pine","green");cache[(t.name,t.texture,t.color)]=t
forest=[(t,(10,20,15)),(t,(30,40,12))]
c.eq("tree intrinsic shared",forest[0][0] is forest[1][0],True)
c.eq("tree extrinsic differs",forest[0][1]!=forest[1][1],True)
del t;gc.collect();c.eq("live forest retains weak cached value",len(cache),1)
forest.clear();gc.collect();c.eq("weak cache releases unused value",len(cache),0)
import html
pieces=[]
for glyph,(x,y)in document:
pieces.append('<text x="'+str(20+x*24)+'" y="40" fill="'+glyph.color+'">'+html.escape(glyph.char)+'</text>')
svg='<svg xmlns="http://www.w3.org/2000/svg" width="240" height="60">'+''.join(pieces)+'</svg>';path=out/"shared-glyphs.svg";path.write_text(svg,encoding="utf8")
c.eq("actual SVG has7placement nodes",len(ET.parse(path).getroot()),7)
def extra_flyweight(c,out):
@dataclass(frozen=True)
class Icon:
source:str
size:int
payload:bytes
path=out/"owned-icon.svg";path.write_text('<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"><circle cx="12" cy="12" r="10" fill="#2563eb"/></svg>',encoding="utf8");cache={};loads=[]
def get_icon(size):
if size not in {24,48}:raise ValueError("supported icon size")
key=(str(path.resolve()),size)
if key not in cache:loads.append(key);cache[key]=Icon(path.name,size,path.read_bytes())
return cache[key]
positions=[(get_icon(24),(0,0)),(get_icon(24),(100,100))];c.eq("icon type shared across positions",positions[0][0]is positions[1][0],True);c.eq("icon actual file loaded once",len(loads),1);c.eq("icon different requested size distinct",get_icon(48)is positions[0][0],False);c.eq("icon bytes actual",positions[0][0].payload,path.read_bytes());c.raises("bad icon size",ValueError,lambda:get_icon(0))
def run_case(out):
c=Checks()
flyweight(c,out)
extra_flyweight(c,out)
return {"chapter":'python-flyweight',"checks":c.rows,"passed":True,"scope":"named owned all24chapter named cases only; full source coverage pending"}
if __name__ == "__main__":
output=Path(sys.argv[1]);output.mkdir(parents=True,exist_ok=False)
print(json.dumps(run_case(output),ensure_ascii=False,default=repr))