codeprobe-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Standalone Mode

独立模式

If invoked directly (not via the orchestrator), you must first:
  1. Read
    ../codeprobe/shared-preamble.md
    for the output contract, execution modes, and constraints.
  2. Load applicable reference files from
    ../codeprobe/references/
    based on the project's tech stack.
  3. Default to
    full
    mode unless the user specifies otherwise.
如果直接调用(不通过编排器),必须先执行以下步骤:
  1. 阅读
    ../codeprobe/shared-preamble.md
    以了解输出约定、执行模式和约束条件。
  2. 根据项目技术栈加载
    ../codeprobe/references/
    中的适用参考文件。
  3. 除非用户另行指定,默认使用
    full
    模式。

Design Patterns Advisor

设计模式顾问

Domain Scope

领域范围

Never recommend a pattern for the sake of it. Only flag a pattern opportunity when a concrete problem exists in the code that the pattern would solve. If the code works, is readable, and is maintainable without a pattern, do not suggest one.
This sub-skill detects two categories of design pattern issues:
  1. Pattern Opportunities — Places where a specific GoF or architectural pattern would solve an observable problem in the code (complexity, duplication, rigidity, hidden dependencies).
  2. Anti-Patterns — Misapplied patterns that add complexity, indirection, or abstraction layers without delivering measurable benefit.

切勿为了使用模式而推荐模式。只有当代码中存在可通过模式解决的具体问题时,才标记模式应用机会。如果代码无需模式就能正常运行、具备可读性且易于维护,则不建议使用模式。
该子技能检测两类设计模式问题:
  1. 模式应用机会——代码中存在可通过特定GoF或架构模式解决的可观测问题(复杂度、重复代码、僵化性、隐藏依赖)的位置。
  2. 反模式——误用的模式,这类模式会增加复杂度、间接性或抽象层,却无法带来可衡量的收益。

What It Does NOT Flag

不标记的内容

  • Switch statements on type/status are already flagged by
    codeprobe-solid
    (OCP-xxx).
    This sub-skill flags them only when it can recommend a specific named pattern (e.g., Strategy, State) with concrete benefits over the current implementation. If the finding would be a generic "consider a pattern here" without naming one, defer to the SOLID auditor. To avoid duplicate findings, check whether the same switch/if-else block would already be covered by an OCP violation. If
    codeprobe-solid
    would flag it and your recommendation is simply "use polymorphism," do not emit a finding. Decision rule: if you can name the pattern, show the interface, and list the concrete implementations, emit a
    PATTERN-
    finding. If you can only say "this violates OCP," let
    codeprobe-solid
    handle it.
  • God classes are already flagged by
    codeprobe-architecture
    (ARCH-xxx).
    This sub-skill only flags them when a specific pattern (e.g., Facade, Mediator) would be the recommended decomposition approach. If the recommendation is simply "split this class," defer to the architecture auditor. Only emit a finding when you can name the exact pattern and explain why it fits better than a generic decomposition. Decision rule: if your fix prompt says "extract into a Facade with these methods," emit a
    PATTERN-
    finding. If it says "break this into smaller classes," let
    codeprobe-architecture
    handle it.
  • Cross-cutting concerns flagged by
    codeprobe-code-smells
    (SMELL-xxx).
    Duplicated logging, caching, or authorization code may already be flagged as code duplication. Only emit a
    PATTERN-
    finding when you recommend a specific pattern (Decorator, Middleware) as the solution. If the duplication is the primary issue, defer to the code smells auditor.
  • Simple scripts or small applications where patterns would be over-engineering. A 50-line CLI script does not need a Strategy pattern. A single-file utility does not need a Factory. Apply proportional design judgment — patterns are tools for managing complexity, not goals in themselves.
  • Code that already implements a pattern correctly — do not suggest replacing one correct pattern with another. If a Factory is working well, do not suggest switching to a Builder unless there is a concrete problem. If a class uses Observer correctly, do not suggest switching to a Mediator.
  • Test files — test utilities and helpers have different design constraints. Test setup classes, fixture builders, and mock factories are not subject to the same pattern expectations as production code. Do not flag test doubles, test data builders, or test orchestration helpers.
  • Low-confidence pattern matches (e.g., Prototype pattern) unless there is strong evidence of cloning behavior. Emit as Suggestion severity at most. When in doubt, do not emit the finding.

  • 基于类型/状态的switch语句已由
    codeprobe-solid
    (OCP-xxx)标记。
    只有当该子技能能推荐具体命名的模式(如Strategy、State)且相比当前实现具备明确收益时,才会标记这类语句。如果只是泛泛地建议“此处可考虑使用模式”却未指明具体模式,则交由SOLID审计工具处理。为避免重复检测,需检查同一switch/if-else块是否已被OCP违规标记。如果
    codeprobe-solid
    会标记该问题,而你的建议仅为“使用多态”,则无需输出检测结果。 判定规则: 若你能明确模式名称、展示接口并列出具体实现,则输出
    PATTERN-
    类型的检测结果。若只能说明“这违反了OCP”,则交由
    codeprobe-solid
    处理。
  • 上帝类已由
    codeprobe-architecture
    (ARCH-xxx)标记。
    只有当特定模式(如Facade、Mediator)是推荐的拆分方案时,该子技能才会标记上帝类。如果建议仅为“拆分此类”,则交由架构审计工具处理。只有当你能明确具体模式并解释其为何比通用拆分更合适时,才输出检测结果。 判定规则: 若你的修复提示为“提取为包含这些方法的Facade”,则输出
    PATTERN-
    类型的检测结果。若提示为“拆分为更小的类”,则交由
    codeprobe-architecture
    处理。
  • 横切关注点已由
    codeprobe-code-smells
    (SMELL-xxx)标记。
    重复的日志、缓存或授权代码可能已被标记为代码重复。只有当你推荐特定模式(如Decorator、Middleware)作为解决方案时,才输出
    PATTERN-
    类型的检测结果。如果核心问题是代码重复,则交由代码异味审计工具处理。
  • 简单脚本或小型应用——使用模式属于过度设计。50行的CLI脚本无需Strategy模式,单文件工具无需Factory模式。需根据实际情况做出合理判断——模式是管理复杂度的工具,而非目标本身。
  • 已正确实现模式的代码——不建议用一种正确模式替换另一种。如果Factory运行良好,除非存在具体问题,否则不建议切换为Builder。如果类已正确使用Observer,不建议切换为Mediator。
  • 测试文件——测试工具和辅助类有不同的设计约束。测试设置类、 fixture构建器和模拟工厂无需遵循生产代码的模式要求。不要标记测试替身、测试数据构建器或测试编排辅助类。
  • 低置信度的模式匹配(如Prototype模式)——除非有明确的克隆行为证据,否则最多标记为建议级别。存疑时,不要输出检测结果。

Detection Instructions

检测说明

Pattern Opportunities

模式应用机会

Observed ProblemCandidate PatternHow to DetectConfidenceSeverity
Complex object construction with 4+ optional paramsBuilderConstructor or factory method with 4+ optional/nullable parameters. Methods that build objects step-by-step using setters then
build()
would be clearer.
HighMinor
Duplicated
new X()
with conditionals scattered across codebase
FactorySearch for
new ClassName()
instantiation of the same family of classes in 3+ locations with surrounding if/switch logic to decide which class to create.
HighMajor
Switch on type to select behavior (when a specific pattern applies)StrategySwitch/if-else chain where each branch executes a different algorithm or behavior — not just returning a value. Must have 3+ branches and the variants are likely to grow. Only flag if NOT already covered by an OCP finding.HighMajor
Object behavior changes based on internal state fieldStateA class with methods containing if/switch on
$this->status
or
this.state
where the same field controls behavior in 3+ methods. State transitions are scattered across the class.
MediumMinor
Multiple listeners need to react to a changeObserver / Event DispatcherA method that directly calls 3+ other services/handlers after a state change (e.g., after order creation: send email, update inventory, notify warehouse, log audit). Should be events.HighMinor
Cross-cutting logic interleaved with business logicDecorator / MiddlewareLogging, caching, authorization, or timing code mixed into business logic methods. Same cross-cutting concern copy-pasted across 3+ methods.HighMajor
God class wrapping a complex subsystemFacadeA large class (300+ LOC) that coordinates multiple subsystems. Clients only need a simplified interface. Only flag when probe-architecture hasn't already flagged as a god object.MediumMinor
Undo/redo or command queue requirementsCommandCode that needs to queue, log, or reverse operations but currently executes them inline.MediumSuggestion
Data flows through conditional transformation stepsPipeline / Chain of ResponsibilityData processed through 3+ sequential if/else transformation steps where each step is conditionally applied. Could be a pipeline of composable stages.MediumMinor
Multiple similar objects differing by a few fieldsPrototypeFactory-like code that creates copies of objects with minor variations.LowSuggestion
观测到的问题候选模式检测方式置信度严重级别
包含4个及以上可选参数的复杂对象构造Builder构造函数或工厂方法包含4个及以上可选/可空参数。使用setter逐步构建对象再调用
build()
的方式会更清晰。
次要
代码库中分散的带条件判断的
new X()
重复代码
Factory搜索代码库中3处及以上位置,同一类族的
new ClassName()
实例化代码周围带有if/switch逻辑以决定创建哪个类。
主要
基于类型切换选择行为(适用特定模式时)StrategySwitch/if-else链中每个分支执行不同的算法行为——而非仅返回值。分支数量需达到3个及以上且可能持续增加。仅当未被OCP检测结果覆盖时才标记。主要
对象行为基于内部状态字段变化State类中的方法包含基于
$this->status
this.state
的if/switch判断,且同一字段控制3个及以上方法的行为。状态转换逻辑分散在类中。
次要
多个监听器需响应变更Observer / Event Dispatcher状态变更后直接调用3个及以上其他服务/处理器的方法(例如订单创建后:发送邮件、更新库存、通知仓库、记录审计日志)。此类场景应使用事件机制。次要
横切逻辑与业务逻辑交织Decorator / Middleware日志、缓存、授权或计时代码混入业务逻辑方法中。同一横切关注点的代码被复制粘贴到3个及以上方法中。主要
包裹复杂子系统的上帝类Facade大型类(300行以上代码)协调多个子系统。客户端仅需简化接口。仅当架构审计工具未标记为上帝对象时才标记。次要
需要撤销/重做或命令队列功能Command需要对操作进行排队、记录或撤销,但当前为内联执行的代码。建议
数据通过条件转换步骤流转Pipeline / Chain of Responsibility数据经过3个及以上顺序执行的if/else转换步骤,每个步骤为条件性应用。可重构为可组合的阶段管道。次要
多个仅少数字段不同的相似对象Prototype类似工厂的代码,创建对象副本并做微小改动。建议

Anti-Patterns (Misapplied Patterns)

反模式(误用的模式)

Anti-PatternWhat to DetectHow to DetectSeverity
Singleton for dependency hidingClass uses
getInstance()
,
static::$instance
, or module-level singleton to access dependencies that should be injected via constructor. The singleton pattern hides dependencies and makes testing difficult.
Search for
getInstance()
,
static::$instance
,
self::$instance
, module-level singleton access patterns in business logic classes. Check whether these dependencies could be injected via constructor instead.
Major
Pass-through RepositoryRepository class wrapping ORM (Eloquent, Doctrine, Prisma) where every method is a 1-line delegation with zero added abstraction, caching, or query logic. The repository adds a layer without value.Find repository classes and check each public method body: if every method is a single-line call to the underlying ORM model with no additional logic, the repository is a pass-through.Minor
Service class that's a renamed controller actionService class with a single public method that exactly mirrors a controller action — same params, same logic, just moved to a different file. Adds indirection without reuse.Find service classes with only one public method. Check if the method signature and logic closely match a corresponding controller action. Look for zero reuse across the codebase (only one caller).Minor
Abstract Factory with one familyAbstract factory interface with only one concrete factory implementation and no foreseeable second implementation. Over-abstraction.Find abstract factory interfaces/classes. Count the number of concrete implementations. If there is exactly one and no indicators of planned expansion (no TODO comments, no documentation mentioning future variants), flag it.Suggestion

反模式检测内容检测方式严重级别
用于隐藏依赖的Singleton类使用
getInstance()
static::$instance
或模块级单例来访问应通过构造函数注入的依赖。单例模式会隐藏依赖并增加测试难度。
搜索业务逻辑类中的
getInstance()
static::$instance
self::$instance
、模块级单例访问模式。检查这些依赖是否可通过构造函数注入。
主要
透传Repository包裹ORM(Eloquent、Doctrine、Prisma)的Repository类,每个方法均为一行委托代码,未添加任何抽象、缓存或查询逻辑。该Repository层无实际价值。查找Repository类并检查每个公共方法体:如果每个方法均为对底层ORM模型的单行调用且无额外逻辑,则该Repository为透传层。次要
重命名的控制器动作Service类仅含一个公共方法的Service类,该方法与控制器动作完全一致——参数相同、逻辑相同,仅移至不同文件。增加了间接性却无复用价值。查找仅含一个公共方法的Service类。检查方法签名和逻辑是否与对应控制器动作高度匹配。查看代码库中是否无复用(仅一个调用方)。次要
仅含一个类族的Abstract Factory抽象工厂接口仅含一个具体工厂实现,且无计划添加第二个实现。属于过度抽象。查找抽象工厂接口/类。统计具体实现数量。如果仅存在一个且无扩展迹象(无TODO注释、无提及未来变体的文档),则标记。建议

ID Prefix & Fix Prompt Examples

ID前缀与修复提示示例

All findings use the
PATTERN-
prefix, numbered sequentially:
PATTERN-001
,
PATTERN-002
, etc.
所有检测结果使用
PATTERN-
前缀,按顺序编号:
PATTERN-001
PATTERN-002
等。

Fix Prompt Examples

修复提示示例

  • "Replace the switch on
    $type
    in
    NotificationSender
    (lines 30-65) with a Strategy pattern: create a
    NotificationChannel
    interface with
    send(Message $message)
    method. Create
    EmailChannel
    ,
    SmsChannel
    , and
    PushChannel
    implementations. Use a
    NotificationChannelFactory
    to resolve the correct channel by type."
  • "Refactor
    ReportBuilder
    constructor (line 15) which takes 7 optional params (
    $title
    ,
    $subtitle
    ,
    $dateRange
    ,
    $format
    ,
    $includeCharts
    ,
    $paperSize
    ,
    $orientation
    ) into a Builder pattern: create
    ReportBuilderConfig
    with fluent setter methods and a
    build()
    method."
  • "The
    AuditLogger
    at
    app/Services/AuditLogger.php
    uses
    AuditLogger::getInstance()
    (line 5) as a singleton. Replace with constructor injection: register
    AuditLogger
    in the DI container as a singleton binding, and inject it via constructor in the 4 classes that currently call
    ::getInstance()
    ."
  • "Remove the
    UserRepositoryInterface
    and
    UserRepository
    wrapper at
    app/Repositories/
    — every method (
    find
    ,
    create
    ,
    update
    ,
    delete
    ) is a single-line delegation to Eloquent with zero added logic. Use the Eloquent model directly until you have a concrete reason for the abstraction."
  • "将
    NotificationSender
    中(第30-65行)基于
    $type
    的switch语句替换为Strategy模式:创建带有
    send(Message $message)
    方法的
    NotificationChannel
    接口,实现
    EmailChannel
    SmsChannel
    PushChannel
    类,使用
    NotificationChannelFactory
    根据类型解析正确的通道。"
  • "将
    ReportBuilder
    构造函数(第15行)的7个可选参数(
    $title
    $subtitle
    $dateRange
    $format
    $includeCharts
    $paperSize
    $orientation
    )重构为Builder模式:创建带有流畅式setter方法和
    build()
    方法的
    ReportBuilderConfig
    类。"
  • "位于
    app/Services/AuditLogger.php
    AuditLogger
    使用
    AuditLogger::getInstance()
    (第5行)作为单例。替换为构造函数注入:在DI容器中注册
    AuditLogger
    为单例绑定,并在当前调用
    ::getInstance()
    的4个类中通过构造函数注入该实例。"
  • "移除
    app/Repositories/
    下的
    UserRepositoryInterface
    UserRepository
    包装类——每个方法(
    find
    create
    update
    delete
    )均为对Eloquent的单行委托,无任何额外逻辑。在有明确抽象需求前,直接使用Eloquent模型。"