桥接:独立变化的抽象和实现
让形状与颜色、消息与通道、遥控器与设备独立组合。
本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。
| 检查项 | 实际结果 | 预期结果 |
|---|---|---|
| circle/red actual SVG paint | "red" | "red" |
| circle/blue actual SVG paint | "blue" | "blue" |
| circle/green actual SVG paint | "green" | "green" |
| circle/yellow actual SVG paint | "yellow" | "yellow" |
| rectangle/red actual SVG paint | "red" | "red" |
| rectangle/blue actual SVG paint | "blue" | "blue" |
| rectangle/green actual SVG paint | "green" | "green" |
| rectangle/yellow actual SVG paint | "yellow" | "yellow" |
| triangle/red actual SVG paint | "red" | "red" |
| triangle/blue actual SVG paint | "blue" | "blue" |
| triangle/green actual SVG paint | "green" | "green" |
| triangle/yellow actual SVG paint | "yellow" | "yellow" |
| ellipse/red actual SVG paint | "red" | "red" |
| ellipse/blue actual SVG paint | "blue" | "blue" |
| ellipse/green actual SVG paint | "green" | "green" |
| ellipse/yellow actual SVG paint | "yellow" | "yellow" |
| switch implementation | true | true |
| unknown color | "ValueError" | "ValueError" |
| TV delegates power | true | true |
| TV delegates volume | 40 | 40 |
| TV delegates mute | 0 | 0 |
| TV clamps at0 | 0 | 0 |
| TV clamps at100 | 100 | 100 |
| TV invalid volume | "ValueError" | "ValueError" |
| radio delegates power | true | true |
| radio delegates volume | 40 | 40 |
| radio delegates mute | 0 | 0 |
| radio clamps at0 | 0 | 0 |
| radio clamps at100 | 100 | 100 |
| radio invalid volume | "ValueError" | "ValueError" |
| message dimension independent of test transport | [["SMS-test", "[紧急] 课程检查"], ["email-test", "学习报告"]] | [["SMS-test", "[紧急] 课程检查"], ["email-test", "学习报告"]] |
| installment cents remainder preserved | [34, 33, 33] | [34, 33, 33] |
| normal payment independent channel | [100] | [100] |
| all test amounts conserved | 200 | 200 |
| invalid combined plan no partial send | "ValueError" | "ValueError" |
| invalid split untouched | 4 | 4 |
| valid split records | [["a", 40], ["b", 60]] | [["a", 40], ["b", 60]] |
本章源码与生成文件
查看当前核心代码
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))
- circle-blue.svg
- circle-green.svg
- circle-red.svg
- circle-yellow.svg
- ellipse-blue.svg
- ellipse-green.svg
- ellipse-red.svg
- ellipse-yellow.svg
- rectangle-blue.svg
- rectangle-green.svg
- rectangle-red.svg
- rectangle-yellow.svg
- triangle-blue.svg
- triangle-green.svg
- triangle-red.svg
- triangle-yellow.svg