蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

单例:对象身份、初始化及并发范围:独立运行与结果核对

PYTHONWindows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Pythonpython-singleton.py
python-singleton.py69 行
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *

def singleton(c,out):
    class Reinitialized:
        _instance=None
        def __new__(cls,name):
            if cls._instance is None: cls._instance=super().__new__(cls)
            return cls._instance
        def __init__(self,name): self.name=name
    a=Reinitialized("first");b=Reinitialized("second")
    c.eq("new-only identity",a is b,True);c.eq("init repeats despite same object",a.name,"second")
    class Config(metaclass=SingletonMeta):
        initializations=0
        def __init__(self,name): type(self).initializations+=1;self.name=name
    class Child(Config): pass
    gate=Barrier(8)
    def get(_): gate.wait(timeout=10);return Config("mbsky")
    with ThreadPoolExecutor(max_workers=8) as pool: results=list(pool.map(get,range(8)))
    c.eq("all actual threads same identity",len({id(x) for x in results}),1)
    c.eq("initialization serialized once",Config.initializations,1)
    c.eq("first arguments retained",Config("ignored").name,"mbsky")
    child=Child("child");c.eq("per-class registry",child is results[0],False)
    c.eq("subclass actual type",type(child) is Child,True)
    # Failed initialization must not publish a partial instance.
    class Retry(metaclass=SingletonMeta):
        attempts=0
        def __init__(self):
            type(self).attempts+=1
            if type(self).attempts==1: raise ValueError("controlled constructor failure")
    c.raises("failed init propagated",ValueError,Retry);Retry();c.eq("failed init retry",Retry.attempts,2)
    module_file=out/"owned_config_module.py";module_file.write_text("instance = object()\n",encoding="utf8")
    name="mbsky_owned_pattern_config_"+out.name
    spec=importlib.util.spec_from_file_location(name,module_file);module=importlib.util.module_from_spec(spec)
    sys.modules[name]=module
    try:
        spec.loader.exec_module(module)
        c.eq("module cache same object",importlib.import_module(name).instance is module.instance,True)
    finally: sys.modules.pop(name,None)

def extra_singleton(c,out):
    def singleton_decorator(cls):
        instance=[];lock=Lock()
        @wraps(cls)
        def get(*args,**kwargs):
            with lock:
                if not instance:instance.append(cls(*args,**kwargs))
                return instance[0]
        return get
    @singleton_decorator
    class CachedConfig:
        def __init__(self):self.values={}
    first=CachedConfig();first.values["site"]="mbsky.com";c.eq("decorator shares config",CachedConfig().values["site"],"mbsky.com");c.raises("decorator replaced class with function",TypeError,lambda:isinstance(first,CachedConfig))
    now=[0];cache=TtlCache(lambda:now[0]);cache.set("a",7,10);now[0]=9;c.eq("ttl before boundary",cache.get("a"),7);now[0]=10;c.eq("ttl exact expiration",cache.get("a"),None);cache.set("b",0,1);c.eq("ttl valid zero",cache.get("b"),0);c.eq("delete cache",cache.delete("b"),True);c.eq("delete missing idempotent",cache.delete("b"),False)
    cfg=ValidatedConfig();seen=[];cfg.listeners.append(seen.append);path=out/"listened-config.json";path.write_text('{"site":"蓝色天空网","debug":true}',encoding="utf8");cfg.load(path);c.eq("validated config listener",seen,[{"site":"蓝色天空网","debug":True}]);seen[0]["site"]="changed";c.eq("listener receives copy",cfg.values["site"],"蓝色天空网")
    path.write_text('{"site":"bad"}',encoding="utf8");c.raises("invalid config no notify",ValueError,lambda:cfg.load(path));c.eq("invalid reload no extra listener call",len(seen),1)

def run_case(out):
    c=Checks()
    singleton(c,out)
    extra_singleton(c,out)
    return {"chapter":'python-singleton',"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-singleton.py

预期结果与验证条件观察提示
  • 当前固定输入命名检查符合明确实际结果及失败策略
  • 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:Python 设计模式

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202611a526.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习