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

桥接:独立变化的抽象和实现:独立运行与结果核对

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

def bridge(c,out):
    for kind in ("circle","rectangle","triangle","ellipse"):
        for color in ("red","blue","green","yellow"):
            shape=Figure(kind,Paint(color));path=out/(kind+"-"+color+".svg");path.write_text(shape.svg(),encoding="utf8")
            node=ET.fromstring(path.read_text(encoding="utf8"));c.eq(kind+"/"+color+" actual SVG paint",node.find("{http://www.w3.org/2000/svg}g").get("fill"),color)
    shape=Figure("ellipse",Paint("yellow"));shape.paint=Paint("blue");c.eq("switch implementation",'fill="blue"' in shape.svg(),True)
    c.raises("unknown color",ValueError,lambda:Paint("script"))
    for name in ("TV","radio"):
        device=DeviceModel(name);basic=Remote(device);advanced=AdvancedRemote(device);basic.toggle();c.eq(name+" delegates power",device.power,True)
        basic.up();c.eq(name+" delegates volume",device.volume,40);advanced.mute();c.eq(name+" delegates mute",device.volume,0)
        basic.down();c.eq(name+" clamps at0",device.volume,0)
        device.set_volume(100);basic.up();c.eq(name+" clamps at100",device.volume,100)
        c.raises(name+" invalid volume",ValueError,lambda:device.set_volume(101))
    recorded=[]
    def sender(channel): return lambda text: recorded.append((channel,text)) or "recorded"
    class Message:
        def __init__(self,send,content,urgent=False):self.send_impl=send;self.content=content;self.urgent=urgent
        def send(self):return self.send_impl(("[紧急] "if self.urgent else "")+self.content)
    Message(sender("SMS-test"),"课程检查",True).send();Message(sender("email-test"),"学习报告").send()
    c.eq("message dimension independent of test transport",recorded,[("SMS-test","[紧急] 课程检查"),("email-test","学习报告")])

def extra_bridge(c,out):
    recorded=[]
    def channel(name):return lambda cents:recorded.append((name,cents))or {"recorded":True}
    def pay_plan(total,parts,send):
        if type(total)is not int or total<=0 or type(parts)is not int or not 1<=parts<=12:raise ValueError("positive cents and1..12parts")
        base,remainder=divmod(total,parts);amounts=[base+(i<remainder)for i in range(parts)]
        for value in amounts:send(value)
        return amounts
    c.eq("installment cents remainder preserved",pay_plan(100,3,channel("bank-test")),[34,33,33]);c.eq("normal payment independent channel",pay_plan(100,1,channel("wallet-test")),[100]);c.eq("all test amounts conserved",sum(v for _,v in recorded),200)
    def split(total,legs):
        if any(type(amount)is not int or amount<=0 for _,amount in legs)or sum(amount for _,amount in legs)!=total:raise ValueError("split plan must conserve total")
        for send,amount in legs:send(amount)
    before=len(recorded);c.raises("invalid combined plan no partial send",ValueError,lambda:split(100,[(channel("a"),30),(channel("b"),60)]));c.eq("invalid split untouched",len(recorded),before);split(100,[(channel("a"),40),(channel("b"),60)]);c.eq("valid split records",recorded[-2:],[("a",40),("b",60)])

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

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

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

附件与关联工程包下载

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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