AgentSkillsCN

gof-design-patterns

检测在 Jakarta EE/MicroProfile 中应用 GoF 设计模式的机会。在审查代码以进行结构改进或实现创建型、结构型或行为型模式时使用。

SKILL.md
--- frontmatter
name: gof-design-patterns
description: Detects opportunities to apply GoF Design Patterns in Jakarta EE/MicroProfile. Use when reviewing code for structural improvements or implementing creational, structural, or behavioral patterns.

GoF Design Patterns Refactoring Detection

Identify opportunities to apply Gang of Four (GoF) Design Patterns in Jakarta EE and MicroProfile applications.


Creational Patterns

Factory Method

Detect: if/switch with new based on type/condition
Refactor: CDI Instance<T> + @Named qualifiers
Cookbook: factory-method.md

Abstract Factory

Detect: Creating families of related objects with scattered logic
Refactor: CDI qualifiers for factory interface implementations
Cookbook: abstract-factory.md

Builder

Detect: Constructors with 4+ parameters, telescoping constructors, many setters in sequence
Refactor: Fluent builder with build() method, immutable objects
Cookbook: builder.md

Singleton

Detect: Manual getInstance() with double-checked locking
Refactor: @ApplicationScoped CDI bean
Cookbook: singleton.md

Prototype

Detect: Expensive object creation, need to copy/clone objects
Refactor: Cloneable interface + prototype registry
Cookbook: prototype.md


Structural Patterns

Adapter

Detect: Interface mismatch with external/legacy APIs
Refactor: CDI bean wrapping legacy system with target interface
Cookbook: adapter.md

Bridge

Detect: Abstraction and implementation should vary independently
Refactor: Separate hierarchy for implementors, inject via CDI
Cookbook: bridge.md

Composite

Detect: Tree/hierarchy structures (menus, org charts, file systems)
Refactor: Recursive interface, JPA @OneToMany self-reference
Cookbook: composite.md

Decorator

Detect: Inheritance explosion, cross-cutting concerns mixed in business logic
Refactor: CDI @Decorator + @Delegate, @Interceptor for AOP
Cookbook: decorator.md

Facade

Detect: Resource/controller calling multiple services directly
Refactor: @ApplicationScoped facade service orchestrating subsystems
Cookbook: facade.md

Flyweight

Detect: Many similar objects causing high memory usage
Refactor: Shared object cache, separate intrinsic/extrinsic state
Cookbook: flyweight.md

Proxy

Detect: Manual lazy loading, scattered access control checks
Refactor: CDI proxies (automatic), @RolesAllowed, MicroProfile REST Client
Cookbook: proxy.md


Behavioral Patterns

Chain of Responsibility

Detect: Sequential handler processing with hardcoded chain
Refactor: CDI Instance<T> + ordering, JAX-RS filters
Cookbook: chain-of-responsibility.md

Command

Detect: Operations needing undo/redo, queuing, or logging
Refactor: Command objects with execute()/undo() + executor
Cookbook: command.md

Interpreter

Detect: DSL/grammar parsing, configurable business rules
Refactor: Expression tree with interpret() method
Cookbook: interpreter.md

Iterator

Detect: Custom traversal needed, lazy loading from database
Refactor: Custom Iterator<T> for paginated queries
Cookbook: iterator.md

Mediator

Detect: Complex inter-object communication, many direct dependencies
Refactor: CDI Events (Event<T> + @Observes) or mediator service
Cookbook: mediator.md

Memento

Detect: Need undo/redo, state snapshots, version history
Refactor: Memento objects + caretaker for history
Cookbook: memento.md

Observer

Detect: Direct method calls to notify multiple dependents
Refactor: CDI Event<T> + @Observes / @ObservesAsync
Cookbook: observer.md

State

Detect: Complex conditionals based on object state (if status == X)
Refactor: State interface with per-state implementations
Cookbook: state.md

Strategy

Detect: switch/if-else selecting between algorithms
Refactor: CDI Instance<T> + strategy selection by qualifier/type
Cookbook: strategy.md

Template Method

Detect: Duplicate algorithm structure with varying steps
Refactor: Abstract class with final template + abstract hooks
Cookbook: template-method.md

Visitor

Detect: Operations across unrelated element types
Refactor: Visitor interface + accept(visitor) in elements
Cookbook: visitor.md


Quick Reference Table

PatternDetection SignalJakarta EE/MP Integration
Factory Methodif/switch with new based on typeCDI Instance<T> + qualifiers
Abstract FactoryCreating families of related objectsCDI qualifiers for factory types
BuilderConstructors with 4+ parametersImmutable objects + fluent API
SingletonManual getInstance() pattern@ApplicationScoped
PrototypeExpensive object creation, need copiesCloneable + prototype registry
AdapterInterface mismatch with external APIsCDI bean wrapping legacy
BridgeAbstraction/implementation should varyCDI for implementor injection
CompositeTree/hierarchy structuresRecursive interface + JPA
DecoratorInheritance for extending behavior@Decorator, @Interceptor
FacadeMultiple service calls in controller@ApplicationScoped facade
FlyweightMany similar objects, high memoryShared caches, object pools
ProxyManual lazy loading / access controlCDI proxies, @RolesAllowed
Chain of ResponsibilitySequential handler processingCDI Instance<T> + ordering
CommandOperations needing undo/queue/logCommand objects + executor
InterpreterDSL/grammar parsing, rule enginesExpression trees + parser
IteratorCustom traversal, lazy DB loadingIterator<T>, paginated queries
MediatorComplex inter-object communicationCDI Events or mediator service
MementoUndo/redo, state snapshotsMemento objects + caretaker
ObserverDirect calls to multiple dependentsCDI Event<T> + @Observes
StateComplex state-based conditionalsState interface + transitions
Strategyswitch/if-else selecting algorithmCDI Instance<T> + iteration
Template MethodDuplicate algorithm with varying stepsAbstract class with hooks
VisitorOperations across unrelated elementsVisitor interface + accept

MicroProfile-Specific Patterns

MP FeaturePattern AppliedExample
Health CheckFactory + Strategy@Liveness, @Readiness implementing HealthCheck
Fault ToleranceDecorator/Proxy@Retry, @Timeout, @Fallback annotations
ConfigStrategy@ConfigProperty to select behavior at runtime
REST ClientProxyInterface-based remote service invocation
MetricsDecorator@Counted, @Timed interceptors

When NOT to Apply Patterns

  1. Simple cases: Don't add Factory for 2-3 types that rarely change
  2. YAGNI: Don't add patterns for "future flexibility"
  3. Performance-critical paths: Pattern overhead may matter
  4. Clear and readable code: Patterns shouldn't obscure intent
  5. Team familiarity: Consider team's pattern knowledge

Cookbook Index

All 23 GoF patterns with Jakarta EE implementations:

Creational (5): Factory Method · Abstract Factory · Builder · Singleton · Prototype

Structural (7): Adapter · Bridge · Composite · Decorator · Facade · Flyweight · Proxy

Behavioral (11): Chain of Responsibility · Command · Interpreter · Iterator · Mediator · Memento · Observer · State · Strategy · Template Method · Visitor