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))
本例需在 Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python
入口文件:projects/patterns-lab/python-flyweight.py
预期结果与验证条件观察提示
- 当前固定输入命名检查符合明确实际结果及失败策略
- 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202611a526.zip