MCPcopy Create free account
hub / github.com/Louisym/MiniCC / lesson_3_builder_pattern

Function lesson_3_builder_pattern

tutorials/18_design_patterns_for_agents.py:345–573  ·  view source on GitHub ↗

对应源码: prompt.rs:85-93 → SystemPromptBuilder 结构体 prompt.rs:95-156 → with_*() 链式调用 + build() 方法 conversation.rs:429-447 → StaticToolExecutor 的 register() 链式调用 permissions.rs:64-73 → PermissionPolicy 的 with_tool_requirement() 问题: 有些对象的参数太多了, 全放构造函数里很痛苦。 比如 Sys

()

Source from the content-addressed store, hash-verified

343# ============================================================
344
345def lesson_3_builder_pattern():
346 """
347 对应源码:
348 prompt.rs:85-93 → SystemPromptBuilder 结构体
349 prompt.rs:95-156 → with_*() 链式调用 + build() 方法
350
351 conversation.rs:429-447 → StaticToolExecutor 的 register() 链式调用
352 permissions.rs:64-73 → PermissionPolicy 的 with_tool_requirement()
353
354 问题: 有些对象的参数太多了, 全放构造函数里很痛苦。
355 比如 SystemPrompt 需要: OS信息、风格、项目上下文、配置、自定义段落...
356 如果写成: SystemPrompt(os, style, ctx, config, sections, ...) — 噩梦!
357
358 Builder 模式: 链式调用, 需要什么加什么, 最后 .build()。
359
360 日常类比: 赛百味点三明治
361 ────────────────────
362 你不会一口气说 "我要全麦面包白面包火鸡肉双倍芝士没有酸黄瓜加墨西哥辣椒"
363 你是一步步选:
364 面包 → 全麦
365 肉 → 火鸡
366 芝士 → 双倍
367 去掉 → 酸黄瓜
368 加上 → 墨西哥辣椒
369 最后说 "好了, 做吧!" → .build()
370 """
371 print("=" * 60)
372 print("第三课: Builder 模式 — 点菜单: 一步步组装复杂对象")
373 print("=" * 60)
374
375 # ---- 反面教材: 参数爆炸 ----
376 print()
377 print(" 反面教材 (参数爆炸):")
378 print(" ──────────────────")
379 print(" SystemPrompt(")
380 print(" os_name='macOS',")
381 print(" os_version='15.0',")
382 print(" style_name='concise',")
383 print(" style_prompt='Be brief',")
384 print(" cwd='/home/user',")
385 print(" date='2024-01-01',")
386 print(" git_status='...',")
387 print(" config=...,")
388 print(" extra_sections=[...],")
389 print(" )")
390 print(" 12 个参数! 大部分可选, 顺序容易搞错。")
391 print()
392
393 # ---- 正面教材: Builder 模式 ----
394
395 # 对应 prompt.rs:85-93 的 SystemPromptBuilder
396 @dataclass
397 class SystemPromptBuilder:
398 """
399 Builder 模式三要素:
400 1. 字段全部可选 (None 默认值)
401 2. with_*() 方法返回 self (链式调用)
402 3. build() 方法组装最终结果

Calls 12

with_projectMethod · 0.80
with_styleMethod · 0.80
SystemPromptBuilderClass · 0.70
StaticToolExecutorClass · 0.70
PermissionPolicyClass · 0.70
buildMethod · 0.45
append_sectionMethod · 0.45
with_osMethod · 0.45
registerMethod · 0.45
executeMethod · 0.45
with_tool_requirementMethod · 0.45
is_allowedMethod · 0.45

Tested by

no test coverage detected