建造者:构建步骤、验证和独立产品
把不完整构建状态限制在builder内,交付稳定的产品。
本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。
| 检查项 | 实际结果 | 预期结果 |
|---|---|---|
| same director different representation | ["office", "gaming"] | ["office", "gaming"] |
| first result not mutated | 16 | 16 |
| independent product identities | false | false |
| missing fields after reset | "ValueError" | "ValueError" |
| invalid memory | "ValueError" | "ValueError" |
| optional optical | true | true |
| constructor alternative keyword dataclass | "Computer(cpu='office', memory=16, storage=512, graphics='integrated', optical=False)" | "Computer(cpu='office', memory=16, storage=512, graphics='integrated', optical=False)" |
| replace does not mutate original | 32 | 32 |
| original still intact | 16 | 16 |
| frozen product rejects mutation | "FrozenInstanceError" | "AttributeError" |
| pizza independent frozen toppings | "extra_builder.<locals>.Meal(size=12, toppings=('cheese', 'mushroom'), cents=4000)" | "extra_builder.<locals>.Meal(size=12, toppings=('cheese', 'mushroom'), cents=4000)" |
| new pizza has extra topping | 4500 | 4500 |
| invalid pizza size | "ValueError" | "ValueError" |
| car components | "electric" | "electric" |
| car incomplete | "ValueError" | "ValueError" |
| computer integer-cent quote | 300000 | 300000 |
本章源码与生成文件
查看当前核心代码
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def builder(c,out):
b=ComputerBuilder();d=Director(b);office=d.office();gaming=d.gaming()
c.eq("same director different representation",[office.cpu,gaming.cpu],["office","gaming"])
c.eq("first result not mutated",office.memory,16)
c.eq("independent product identities",office is gaming,False)
c.raises("missing fields after reset",ValueError,b.build)
c.raises("invalid memory",ValueError,lambda:b.cpu("x").memory(2).storage(32).build())
good=b.reset().cpu("custom").memory(64).storage(4000).optical(True).build()
c.eq("optional optical",good.optical,True)
c.eq("constructor alternative keyword dataclass",Computer(cpu="office",memory=16,storage=512),office)
c.eq("replace does not mutate original",replace(office,memory=32).memory,32)
c.eq("original still intact",office.memory,16)
c.raises("frozen product rejects mutation",AttributeError,lambda:setattr(office,"memory",128))
def extra_builder(c,out):
@dataclass(frozen=True)
class Meal:
size:int
toppings:tuple
cents:int
class PizzaBuilder:
def __init__(self,size):
if size not in {8,12,16}:raise ValueError("size8/12/16")
self.size=size;self.toppings=[]
def add(self,topping):
if topping not in {"cheese","pepperoni","mushroom"}:raise ValueError("topping")
if topping not in self.toppings:self.toppings.append(topping)
return self
def build(self):return Meal(self.size,tuple(self.toppings),{8:2000,12:3000,16:4000}[self.size]+500*len(self.toppings))
builder=PizzaBuilder(12).add("cheese").add("mushroom");pizza=builder.build();builder.add("pepperoni");c.eq("pizza independent frozen toppings",pizza,Meal(12,("cheese","mushroom"),4000));c.eq("new pizza has extra topping",builder.build().cents,4500);c.raises("invalid pizza size",ValueError,lambda:PizzaBuilder(0))
@dataclass(frozen=True)
class Car:
engine:str
color:str
wheels:int
interior:str
class CarBuilder:
def __init__(self):self.parts={}
def set(self,**parts):self.parts.update(parts);return self
def build(self):
p=self.parts
if set(p)!={"engine","color","wheels","interior"}or p["engine"]not in {"gas","electric","hybrid"}or p["color"]not in {"red","blue","black","white"}or p["wheels"]not in {16,18,20}or p["interior"]not in {"leather","cloth"}:raise ValueError("car component schema")
result=Car(**p);self.parts={};return result
car=CarBuilder().set(engine="electric",color="blue",wheels=18,interior="cloth").build();c.eq("car components",car.engine,"electric");c.raises("car incomplete",ValueError,CarBuilder().build)
prices={"office":300000,"gaming":700000};computer=Director(ComputerBuilder()).office();c.eq("computer integer-cent quote",prices[computer.cpu]+(10000 if computer.optical else 0),300000)
def run_case(out):
c=Checks()
builder(c,out)
extra_builder(c,out)
return {"chapter":'python-builder',"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))