design-patterns

Software design patterns for Python and C++ development. Use when implementing creational patterns (Factory, Builder, Singleton), structural patterns (Adapter, Decorator, Facade), or behavioral patterns (Strategy, Observer, Command). Covers Gang of Four patterns with language-specific implementations, when to use each pattern, and common anti-patterns to avoid.

$ 설치

git clone https://github.com/majiayu000/claude-skill-registry /tmp/claude-skill-registry && cp -r /tmp/claude-skill-registry/skills/development/design-patterns ~/.claude/skills/claude-skill-registry

// tip: Run this command in your terminal to install the skill


name: design-patterns description: Software design patterns for Python and C++ development. Use when implementing creational patterns (Factory, Builder, Singleton), structural patterns (Adapter, Decorator, Facade), or behavioral patterns (Strategy, Observer, Command). Covers Gang of Four patterns with language-specific implementations, when to use each pattern, and common anti-patterns to avoid.

Software Design Patterns

Purpose

Guide for applying classic software design patterns in Python and C++ codebases. Patterns help solve common design problems with proven, reusable solutions.

When to Use This Skill

Automatically activates when working on:

  • Creating factories or builders
  • Implementing plugin systems
  • Decoupling components
  • Managing object creation complexity
  • Adding extensibility to existing code
  • Refactoring tightly-coupled code

Pattern Categories

CategoryPurposeCommon Patterns
CreationalObject creation mechanismsFactory, Builder, Singleton
StructuralObject compositionAdapter, Decorator, Facade
BehavioralObject communicationStrategy, Observer, Command

Quick Reference: When to Use Each Pattern

ProblemPatternKey Benefit
Create objects without specifying exact classFactoryDecouples creation from usage
Complex object with many optional parametersBuilderReadable, step-by-step construction
Ensure only one instance existsSingletonGlobal access (use sparingly!)
Make incompatible interfaces work togetherAdapterIntegration without modification
Add behavior without modifying classDecoratorRuntime extension
Simplify complex subsystemFacadeSingle entry point
Swap algorithms at runtimeStrategyFlexible behavior
Notify multiple objects of changesObserverLoose coupling
Encapsulate requests as objectsCommandUndo/redo, queuing

Most Common Patterns (Quick Examples)

Factory Method

# Python
class ControllerFactory:
    _controllers = {"joint": JointController, "cartesian": CartesianController}

    @classmethod
    def create(cls, controller_type: str) -> Controller:
        return cls._controllers[controller_type]()

controller = ControllerFactory.create("joint")
// C++
class ControllerFactory {
public:
    static std::unique_ptr<Controller> Create(const std::string& type) {
        if (type == "joint") return std::make_unique<JointController>();
        if (type == "cartesian") return std::make_unique<CartesianController>();
        throw std::invalid_argument("Unknown type");
    }
};

Builder

# Python - Fluent builder
config = (
    RobotConfigBuilder("Apollo", joint_count=7)
    .with_velocity(2.0)
    .with_collision(False)
    .build()
)
// C++
auto config = RobotConfig::Builder("Apollo", 7)
    .WithVelocity(2.0)
    .WithCollision(false)
    .Build();

Strategy

# Python - Swap algorithms at runtime
class MotionController:
    def __init__(self, generator: TrajectoryGenerator) -> None:
        self._generator = generator

    def set_generator(self, generator: TrajectoryGenerator) -> None:
        self._generator = generator

    def move(self, start: float, end: float) -> np.ndarray:
        return self._generator.generate(start, end)

controller = MotionController(LinearTrajectory())
controller.set_generator(CubicTrajectory())  # Swap at runtime

Observer

# Python - Publish/subscribe
class StatePublisher:
    def __init__(self) -> None:
        self._observers: list[StateObserver] = []

    def subscribe(self, observer: StateObserver) -> None:
        self._observers.append(observer)

    def update_state(self, state: RobotState) -> None:
        for observer in self._observers:
            observer.on_state_change(state)

publisher = StatePublisher()
publisher.subscribe(Logger())
publisher.subscribe(SafetyMonitor())

Decorator

# Python - Add behavior via decorators
@timing
@retry(max_attempts=3)
@log_calls
def send_command(joint_id: int, position: float) -> bool:
    ...

Facade

# Python - Simplify complex subsystem
class RobotFacade:
    def move_to(self, target: Pose) -> bool:
        if not self._safety.is_safe():
            return False
        trajectory = self._motion.plan(target)
        if self._collision.check(trajectory):
            return False
        return self._controller.execute(trajectory)

robot = RobotFacade()
robot.move_to(target_pose)  # Simple interface

Choosing the Right Pattern

Creational Patterns

PatternChoose When
FactoryDon't know exact class until runtime
Abstract FactoryNeed families of related objects
BuilderMany optional parameters, complex construction
SingletonExactly one instance needed (hardware, config)
PrototypeCloning is cheaper than creating

Structural Patterns

PatternChoose When
AdapterConverting interface A to interface B
DecoratorAdding behavior without subclassing
FacadeSimplifying complex API
CompositeTree structures, part-whole hierarchies
ProxyLazy loading, access control, caching
BridgeAbstraction and implementation vary independently

Behavioral Patterns

PatternChoose When
StrategyMultiple interchangeable algorithms
ObserverOne-to-many event notification
CommandUndo/redo, request queuing
StateBehavior depends on object state
Template MethodCommon algorithm, varying steps
Chain of ResponsibilityMultiple potential handlers

Anti-Patterns to Avoid

Singleton overuse - Hides dependencies, makes testing hard ❌ God object - One class that does everything ❌ Premature abstraction - Adding patterns before they're needed ❌ Pattern mania - Using patterns for their own sake ❌ Ignoring YAGNI - Building extensibility you'll never use


Pattern Selection Flowchart

Need to create objects?
├── Don't know class until runtime → Factory
├── Many optional parameters → Builder
├── Need exactly one instance → Singleton (carefully!)
└── Need related object families → Abstract Factory

Need to structure objects?
├── Convert interface → Adapter
├── Add behavior dynamically → Decorator
├── Simplify complex API → Facade
└── Tree structure → Composite

Need to manage behavior?
├── Swap algorithms → Strategy
├── Notify on changes → Observer
├── Undo/redo support → Command
└── State-dependent behavior → State

Resource Files

creational-patterns.md

Factory, Abstract Factory, Builder, Prototype, Singleton with full examples

structural-patterns.md

Adapter, Bridge, Composite, Decorator, Facade, Proxy with full examples

behavioral-patterns.md

Strategy, Observer, Command, State, Template Method, Chain of Responsibility


Related Resources


Skill Status: COMPLETE ✅ Line Count: < 450 ✅ Progressive Disclosure: Resource files for detailed patterns ✅