AgentSkillsCN

design-patterns

四人帮(GoF)设计模式——由伽玛、赫尔姆、约翰逊与弗利西德斯整理的23种成熟面向对象解决方案,分为创建型、结构型与行为型三大类。 适用场景:GoF设计模式、模式选择、面向对象设计、创建型/结构型/行为型模式、组合优于继承。 不适用场景:企业消息传递模式(使用Dev/Integration-Patterns)、架构风格(使用Dev/Architecture)、算法选择(使用Dev/Algorithms)。

SKILL.md
--- frontmatter
name: design-patterns
description: |
    Gang of Four (GoF) design patterns — 23 proven object-oriented solutions organized into Creational, Structural, and Behavioral categories, drawn from Gamma, Helm, Johnson, and Vlissides.
    USE FOR: GoF design patterns, pattern selection, object-oriented design, creational/structural/behavioral patterns, composition over inheritance
    DO NOT USE FOR: enterprise messaging patterns (use dev/integration-patterns), architecture styles (use dev/architecture), algorithm selection (use dev/algorithms)
license: MIT
metadata:
  displayName: "Design Patterns (GoF)"
  author: "Tyler-R-Kendrick"
compatibility: claude, copilot, cursor

Design Patterns (Gang of Four)

Overview

The 23 Gang of Four (GoF) design patterns, catalogued by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides in Design Patterns: Elements of Reusable Object-Oriented Software (1994), remain the foundational vocabulary for object-oriented design. Each pattern captures a recurring design problem, its context, and a proven solution structure.

Core Principles

Program to an Interface, Not an Implementation

Depend on abstractions (interfaces / abstract classes), not concrete classes. This decouples code from specific implementations, making it easier to swap, mock, and extend behavior.

typescript
// Bad — coupled to concrete class
const logger = new FileLogger();

// Good — coupled to abstraction
const logger: Logger = createLogger(); // returns FileLogger, ConsoleLogger, etc.

Favor Composition Over Inheritance

Build complex behavior by composing objects that delegate to each other rather than extending deep class hierarchies. Most GoF patterns are variations of this principle.

typescript
// Inheritance — rigid, one axis of variation
class LoggingHttpClient extends HttpClient { ... }

// Composition — flexible, multiple axes of variation
class HttpClient {
  constructor(private logger: Logger, private cache: Cache) {}
}

The Open/Closed Principle

Classes should be open for extension but closed for modification. Patterns like Strategy, Decorator, and Observer let you add new behavior without changing existing code.

Pattern Categories

code
┌──────────────────────────────────────────────────────────────┐
│                     GoF Design Patterns                      │
├────────────────┬─────────────────────┬───────────────────────┤
│  Creational    │  Structural         │  Behavioral           │
│  (5 patterns)  │  (7 patterns)       │  (11 patterns)        │
│                │                     │                       │
│  Factory       │  Adapter            │  Chain of Resp.       │
│  Method        │  Bridge             │  Command              │
│  Abstract      │  Composite          │  Interpreter          │
│  Factory       │  Decorator          │  Iterator             │
│  Builder       │  Facade             │  Mediator             │
│  Prototype     │  Flyweight          │  Memento              │
│  Singleton     │  Proxy              │  Observer             │
│                │                     │  State                │
│                │                     │  Strategy             │
│                │                     │  Template Method      │
│                │                     │  Visitor              │
└────────────────┴─────────────────────┴───────────────────────┘

Quick-Reference Table — All 23 Patterns

Creational Patterns

PatternOne-Line Description
Factory MethodDefer instantiation to subclasses via a factory method
Abstract FactoryCreate families of related objects without specifying concrete classes
BuilderConstruct complex objects step by step with a fluent interface
PrototypeCreate new objects by cloning an existing instance
SingletonEnsure a class has exactly one instance with a global access point

Structural Patterns

PatternOne-Line Description
AdapterConvert one interface into another that clients expect
BridgeSeparate an abstraction from its implementation so both can vary
CompositeCompose objects into tree structures; treat leaf and node uniformly
DecoratorAttach additional responsibilities to an object dynamically
FacadeProvide a simplified interface to a complex subsystem
FlyweightShare fine-grained objects to support large quantities efficiently
ProxyProvide a surrogate to control access, caching, or lazy loading

Behavioral Patterns

PatternOne-Line Description
Chain of ResponsibilityPass a request along a chain of handlers until one processes it
CommandEncapsulate a request as an object to support undo, redo, and queuing
InterpreterDefine a grammar and an interpreter to evaluate expressions
IteratorProvide sequential access to elements without exposing internals
MediatorCentralize complex communications between related objects
MementoCapture and restore an object's internal state without violating encapsulation
ObserverNotify dependent objects automatically when state changes
StateAlter an object's behavior when its internal state changes
StrategyDefine a family of interchangeable algorithms behind a common interface
Template MethodDefine a skeleton algorithm; let subclasses override specific steps
VisitorAdd new operations to a class hierarchy without modifying the classes

Pattern Selection Guide

When You Need To...Use This Pattern
Create objects without specifying exact classesFactory Method or Abstract Factory
Build an object with many optional partsBuilder
Copy an existing configured objectPrototype
Guarantee exactly one instanceSingleton (use sparingly)
Make incompatible interfaces work togetherAdapter
Vary abstraction and implementation independentlyBridge
Represent part-whole hierarchies uniformlyComposite
Add behavior without subclassingDecorator
Simplify access to a complex subsystemFacade
Reduce memory usage for many similar objectsFlyweight
Control or augment access to an objectProxy
Decouple senders from receivers along a chainChain of Responsibility
Support undo/redo or queue operationsCommand
Traverse a collection without exposing structureIterator
Reduce coupling between many communicating objectsMediator
Snapshot and restore object stateMemento
React to state changes in another objectObserver
Change behavior based on internal stateState
Swap algorithms at runtimeStrategy
Reuse an algorithm skeleton with varying stepsTemplate Method
Add operations across a class hierarchy without changing itVisitor
Evaluate structured expressions or grammarsInterpreter

Relationships Between Patterns

code
Factory Method ──evolves into──▶ Abstract Factory
Builder ──often uses──▶ Composite (to build trees)
Decorator ──similar structure──▶ Proxy (but different intent)
Strategy ──similar to──▶ State (but Strategy is stateless swap)
Command ──can use──▶ Memento (for undo)
Observer ──can be replaced by──▶ Mediator (when N:M gets complex)
Composite ──often paired with──▶ Iterator (to traverse)
Composite ──often paired with──▶ Visitor (to add operations)
Template Method ──class-based version of──▶ Strategy

Anti-Pattern Warnings

  • Singleton abuse: Often masks global mutable state. Prefer dependency injection. Use only when a single instance is a hard requirement (e.g., thread pool, hardware access).
  • Pattern overuse: Not every class needs a pattern. Apply patterns when you encounter the specific problem they solve, not preemptively.
  • Wrong pattern choice: Strategy and State look similar but solve different problems. Adapter and Facade both wrap objects but with different intent. Read the intent section of each pattern carefully.

Sub-Skills

  • dev/design-patterns/creational — Factory Method, Abstract Factory, Builder, Prototype, Singleton
  • dev/design-patterns/structural — Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy
  • dev/design-patterns/behavioral — Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor