+ );
+}
diff --git a/site/src/components/search/SearchResults.tsx b/site/src/components/search/SearchResults.tsx
new file mode 100644
index 0000000..da1a4b5
--- /dev/null
+++ b/site/src/components/search/SearchResults.tsx
@@ -0,0 +1,44 @@
+import type { PatternRecord } from "../../types/pattern";
+import { intentChips } from "../../lib/search";
+import { PatternCard } from "../patterns/PatternCard";
+
+export function SearchResults(props: {
+ patterns: PatternRecord[];
+ query: string;
+ onSuggestionClick?: (value: string) => void;
+}) {
+ const { patterns, query, onSuggestionClick } = props;
+
+ if (!patterns.length) {
+ return (
+
+
No exact matches
+
+ Try a broader term, switch categories, or jump to one of these search prompts.
+
+ {onSuggestionClick ? (
+
+ {intentChips.map((chip) => (
+
+ ))}
+
+ ) : null}
+
+ );
+ }
+
+ return (
+
+ {patterns.map((pattern) => (
+
+ ))}
+
+ );
+}
diff --git a/site/src/content/patterns.json b/site/src/content/patterns.json
new file mode 100644
index 0000000..c41c713
--- /dev/null
+++ b/site/src/content/patterns.json
@@ -0,0 +1,5306 @@
+[
+ {
+ "id": "abstract-factory",
+ "slug": "abstract-factory",
+ "name": "Abstract Factory",
+ "category": "gof",
+ "subcategory": "creational",
+ "summary": "The Abstract Factory pattern Provides an interface for creating families of related or dependent objects without specifying their concrete classes.",
+ "intent": "The Abstract Factory pattern Provides an interface for creating families of related or dependent objects without specifying their concrete classes.",
+ "applicability": [
+ "When simpler solutions suffice",
+ "When adding unnecessary complexity",
+ "In performance-critical paths (if it introduces overhead)"
+ ],
+ "advantages": [
+ "Isolates client from concrete classes",
+ "Ensures consistency among related products",
+ "Easy to swap product families",
+ "Centrali"
+ ],
+ "disadvantages": [
+ "More interfaces/classes required",
+ "Complex hierarchy",
+ "Adding new product type affects all factories",
+ "Overkill for simple scenarios"
+ ],
+ "tradeOffs": [],
+ "alternatives": [
+ "When simpler solutions suffice",
+ "When adding unnecessary complexity",
+ "In performance-critical paths (if it introduces overhead)"
+ ],
+ "keywords": [
+ "Abstract Factory",
+ "gof",
+ "creational",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "design principles",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns",
+ "real-world use cases",
+ "alternatives similar patterns",
+ "best practices",
+ "related patterns",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "🔀 Design Principles",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns",
+ "🌍 Real-World Use Cases",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "🎓 Related Patterns",
+ "📚 References",
+ "The",
+ "Abstract",
+ "Factory",
+ "pattern",
+ "Provides",
+ "interface",
+ "for",
+ "creating",
+ "families",
+ "related",
+ "dependent",
+ "objects",
+ "without",
+ "specifying",
+ "their",
+ "concrete",
+ "classes",
+ "object creation",
+ "family of objects"
+ ],
+ "aliases": [
+ "abstract factory",
+ "AF"
+ ],
+ "tags": [
+ "gof",
+ "creational",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "design principles",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns",
+ "real-world use cases",
+ "alternatives similar patterns",
+ "best practices",
+ "related patterns",
+ "references"
+ ],
+ "githubPath": "gof-patterns/abstract-factory",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/abstract-factory",
+ "demoCodePaths": [
+ "gof-patterns/abstract-factory/src/main/java",
+ "gof-patterns/abstract-factory/src/main",
+ "gof-patterns/abstract-factory/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 2,
+ "contentHtml": "
Abstract Factory Pattern
\n
📋 Overview
\n
The Abstract Factory pattern - Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
You need to create families of related objects while ensuring they work together correctly; switch between families without modifying client code.
\n
\n
Use When:
\n
\n
Your system needs multiple families of related products
\n
Ensure only compatible family members are used
\n
Switch between product families dynamically
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
AbstractFactory
\n
Interface for creating products
\n
\n
\n
ConcreteFactory
\n
Implements product creation
\n
\n
\n
AbstractProduct
\n
Product interface
\n
\n
\n
ConcreteProduct
\n
Concrete implementations
\n
\n\n
\n\n
💡 Code Example
\n
java
// Abstract Factory\npublicinterfaceKingdomFactory {\n Castle createCastle();\n King createKing();\n Army createArmy();\n}\n\n// Concrete Factories\npublicclassElfKingdomFactoryimplementsKingdomFactory {\n public Castle createCastle() { returnnewElfCastle(); }\n public King createKing() { returnnewElfKing(); }\n public Army createArmy() { returnnewElfArmy(); }\n}\n\npublicclassDwarfKingdomFactoryimplementsKingdomFactory {\n public Castle createCastle() { returnnewDwarfCastle(); }\n public King createKing() { returnnewDwarfKing(); }\n public Army createArmy() { returnnewDwarfArmy(); }\n}\n\n// Usage\nKingdomFactoryfactory=newElfKingdomFactory();\nCastlecastle= factory.createCastle();\n
Reasoning: Client code doesn’t know concrete classes. Entire family changes by swapping factory. Ensures type-safe product combinations.
\n\n
🔀 Design Principles
\n
\n
Dependency Inversion
\n
Single Responsibility
\n
Open/Closed Principle
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Client\n class AbstractFactory {\n <<interface>>\n +createProductA()\n +createProductB()\n }\n class ConcreteFactory1\n class ConcreteFactory2\n class AbstractProductA {\n <<interface>>\n }\n class AbstractProductB {\n <<interface>>\n }\n class ProductA1\n class ProductA2\n class ProductB1\n class ProductB2\n AbstractFactory <|-- ConcreteFactory1\n AbstractFactory <|-- ConcreteFactory2\n AbstractProductA <|-- ProductA1\n AbstractProductA <|-- ProductA2\n AbstractProductB <|-- ProductB1\n AbstractProductB <|-- ProductB2\n ConcreteFactory1 --> ProductA1\n ConcreteFactory1 --> ProductB1\n ConcreteFactory2 --> ProductA2\n ConcreteFactory2 --> ProductB2\n AbstractFactory --> AbstractProductA\n AbstractFactory --> AbstractProductB\n Client --> AbstractFactory\n Client --> AbstractProductA\n Client --> AbstractProductB\n
For simple scenarios where direct solutions suffice
\n
When performance is critical and overhead is unacceptable
\n
In situations where the pattern doesn’t naturally fit
\n
\n\n
⚠️ Common Anti-Patterns
\n
\n\n
\n
Anti-Pattern
\n
Issue
\n
Solution
\n
\n\n\n
\n
Overuse
\n
Using pattern unnecessarily
\n
Apply YAGNI principle
\n
\n
\n
Misapplication
\n
Wrong context for pattern
\n
Study pattern requirements
\n
\n
\n
Complexity
\n
Pattern makes code harder
\n
Simplify or choose different pattern
\n
\n\n
\n\n
🌍 Real-World Use Cases
\n
This pattern appears frequently in:
\n
\n
Enterprise applications
\n
Framework and library design
\n
System integration scenarios
\n
\n\n
🔗 Alternatives & Similar Patterns
\n
\n
Other structural/behavioral patterns
\n
Simpler direct approaches
\n
Complementary patterns
\n
\n\n
📝 Best Practices
\n\n
Understand the problem before applying the pattern
\n
Document your pattern usage clearly
\n
Keep implementations simple
\n
Test thoroughly
\n
Consider performance implications
\n
Review periodically for improvements
\n
Teach team members about the pattern
\n
Refactor if pattern no longer applies
\n\n\n
📚 References
\n
\n
Gang of Four Design Patterns
\n
Effective Java (Joshua Bloch)
\n
Design Patterns in Java
\n
Refactoring Guru
\n
\n
For detailed implementation, see the source files in src/.
\n",
+ "contentMarkdown": "# Bridge Pattern\n\n## 📋 Overview\n\nThis folder contains the **Bridge** design pattern implementation.\n\n---\n\n## 🎯 Intent\n\nThe bridge pattern solves a specific structural or behavioral problem in software design by providing reusable solutions.\n\n---\n\n## 👥 Roles & Responsibilities\n\nThis pattern involves multiple roles working together to achieve separation of concerns and flexibility.\n\n---\n\n## 💡 Code Example\n\nPlease see the `src/` directory for complete, executable code examples demonstrating this pattern.\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Abstraction {\n -implementor: Implementor\n +operation()\n }\n class RefinedAbstraction\n class Implementor {\n <>\n +operationImpl()\n }\n class ConcreteImplementorA\n class ConcreteImplementorB\n Client --> Abstraction\n Abstraction <|-- RefinedAbstraction\n Implementor <|-- ConcreteImplementorA\n Implementor <|-- ConcreteImplementorB\n Abstraction --> Implementor\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>Abstraction: operation()\n Abstraction->>Implementor: operationImpl()\n Implementor-->>Abstraction: result\n Abstraction-->>Client: result\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Provides structured solution\n- Promotes code reusability\n- Improves maintainability\n\n### Disadvantages ❌\n- May add complexity\n- Performance overhead\n- Learning curve\n\n---\n\n## 🚫 When NOT to Use\n\n- For simple scenarios where direct solutions suffice\n- When performance is critical and overhead is unacceptable\n- In situations where the pattern doesn't naturally fit\n\n---\n\n## ⚠️ Common Anti-Patterns\n\n| Anti-Pattern | Issue | Solution |\n|--------------|-------|----------|\n| Overuse | Using pattern unnecessarily | Apply YAGNI principle |\n| Misapplication | Wrong context for pattern | Study pattern requirements |\n| Complexity | Pattern makes code harder | Simplify or choose different pattern |\n\n---\n\n## 🌍 Real-World Use Cases\n\nThis pattern appears frequently in:\n- Enterprise applications\n- Framework and library design\n- System integration scenarios\n\n---\n\n## 🔗 Alternatives & Similar Patterns\n\n- Other structural/behavioral patterns\n- Simpler direct approaches\n- Complementary patterns\n\n---\n\n## 📝 Best Practices\n\n1. Understand the problem before applying the pattern\n2. Document your pattern usage clearly\n3. Keep implementations simple\n4. Test thoroughly\n5. Consider performance implications\n6. Review periodically for improvements\n7. Teach team members about the pattern\n8. Refactor if pattern no longer applies\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Effective Java (Joshua Bloch)\n- Design Patterns in Java\n- Refactoring Guru\n\nFor detailed implementation, see the source files in `src/`.",
+ "relatedPatternIds": [
+ "adapter",
+ "composite",
+ "decorator",
+ "facade"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns",
+ "🌍 Real-World Use Cases",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "📚 References"
+ ],
+ "excerpt": "Bridge Pattern 📋 Overview This folder contains the Bridge design pattern implementation. 👥 Roles & Responsibilities This pattern involves multiple roles working together to achieve separation of concerns and flexibility. 💡 Code Example Please see the src/ d",
+ "featured": false,
+ "previewImage": "/pattern-previews/bridge.svg",
+ "previewThumbnailImage": "/pattern-previews/bridge.svg"
+ },
+ {
+ "id": "builder",
+ "slug": "builder",
+ "name": "Builder",
+ "category": "gof",
+ "subcategory": "creational",
+ "summary": "The Builder Pattern is a creational pattern that constructs complex objects step by step, separating the construction logic from the representation. It provides a fluent, readable interface for building objects with many optional parameters or complex initialization logic.",
+ "intent": "The Builder Pattern is a creational pattern that constructs complex objects step by step, separating the construction logic from the representation. It provides a fluent, readable interface for building objects with many optional parameters or complex initialization logic.",
+ "applicability": [
+ "Scenario Why Avoid Simple Objects Objects with 1 2 parameters",
+ "use direct constructors Mutable Objects Builder is designed for immutability",
+ "doesn't benefit mutable objects Performance Critical Memory overhead of builder may matter in high frequency scenarios All Parameters Optional If no mandatory parameters, builder doesn't enforce constraints Frequent Modification If object needs modification after creation, use setters instead"
+ ],
+ "advantages": [
+ "**Improved Readability:** Fluent interface makes code self-documenting",
+ "**Flexibility:** Easy to add/remove optional parameters without breaking code",
+ "**Immutability:** Separating construction enables creation of immutable objects",
+ "**Complex Initiali"
+ ],
+ "disadvantages": [
+ "**Code Verbosity:** More classes and methods to maintain",
+ "**Performance Overhead:** Creating builder object adds memory/GC pressure",
+ "**Complexity for Simple Objects:** Overkill for objects with few parameters",
+ "**Thread Safety:** Builder itself is not thread-safe; don't share across threads",
+ "**Builder Proliferation:** Every complex class needs its own builder"
+ ],
+ "tradeOffs": [],
+ "alternatives": [
+ "Scenario Why Avoid Simple Objects Objects with 1 2 parameters",
+ "use direct constructors Mutable Objects Builder is designed for immutability",
+ "doesn't benefit mutable objects Performance Critical Memory overhead of builder may matter in high frequency scenarios All Parameters Optional If no mandatory parameters, builder doesn't enforce constraints Frequent Modification If object needs modification after creation, use setters instead"
+ ],
+ "keywords": [
+ "Builder",
+ "gof",
+ "creational",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation example",
+ "class diagram",
+ "sequence diagram",
+ "design principles emphasized",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns misuses",
+ "real-world use cases",
+ "java stringbuilder",
+ "google guava - immutablelist",
+ "lombok builder",
+ "http clients okhttp",
+ "apache commons - configuration",
+ "alternatives similar patterns",
+ "best practices",
+ "related patterns",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "🔀 Design Principles Emphasized",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns & Misuses",
+ "🌍 Real-World Use Cases",
+ "Lombok @Builder",
+ "HTTP Clients (OkHttp)",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "🎓 Related Patterns",
+ "📚 References",
+ "The",
+ "Pattern",
+ "that",
+ "constructs",
+ "complex",
+ "objects",
+ "step",
+ "separating",
+ "construction",
+ "logic",
+ "from",
+ "representation",
+ "provides",
+ "fluent",
+ "readable",
+ "interface",
+ "for",
+ "building",
+ "with",
+ "many",
+ "optional",
+ "parameters",
+ "initialization"
+ ],
+ "aliases": [
+ "builder"
+ ],
+ "tags": [
+ "gof",
+ "creational",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation example",
+ "class diagram",
+ "sequence diagram",
+ "design principles emphasized",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns misuses",
+ "real-world use cases",
+ "java stringbuilder",
+ "google guava - immutablelist",
+ "lombok builder",
+ "http clients okhttp",
+ "apache commons - configuration",
+ "alternatives similar patterns",
+ "best practices",
+ "related patterns",
+ "references"
+ ],
+ "githubPath": "gof-patterns/builder",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/builder",
+ "demoCodePaths": [
+ "gof-patterns/builder/src/main/java",
+ "gof-patterns/builder/src/main",
+ "gof-patterns/builder/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 4,
+ "contentHtml": "
Builder Pattern
\n
📋 Overview
\n
The Builder Pattern is a creational pattern that constructs complex objects step-by-step, separating the construction logic from the representation. It provides a fluent, readable interface for building objects with many optional parameters or complex initialization logic.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Creating objects with many parameters is error-prone and produces unreadable code
\n
Objects have optional and mandatory parameters; telescoping constructors become unwieldy
\n
Complex initialization logic should be separated from object representation
\n
You need to construct immutable objects while maintaining readability
\n
\n
Use When:
\n
\n
Objects have 3+ optional parameters
\n
You need to build immutable objects with validation
\n
Construction logic is complex or multi-step
\n
You want to improve code readability over constructor overloading
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Product
\n
The complex object being constructed (e.g., Hero)
\n
\n
\n
Builder
\n
Abstract interface defining construction steps
\n
\n
\n
Concrete Builder
\n
Implements construction steps, accumulates result
\n
\n
\n
Director
\n
(Optional) Orchestrates the builder to construct products in a specific order
classDiagram\n class Client\n class Director {\n -builder: Builder\n +construct()\n }\n class Builder {\n <<interface>>\n +buildPartA()\n +buildPartB()\n +getResult()\n }\n class ConcreteBuilder\n class Product\n Client --> Director\n Director --> Builder\n Builder <|-- ConcreteBuilder\n ConcreteBuilder --> Product\n
Complexity for Simple Objects: Overkill for objects with few parameters
\n
Thread Safety: Builder itself is not thread-safe; don’t share across threads
\n
Builder Proliferation: Every complex class needs its own builder
\n
\n\n
🚫 When NOT to Use
\n
\n\n
\n
Scenario
\n
Why Avoid
\n
\n\n\n
\n
Simple Objects
\n
Objects with 1-2 parameters; use direct constructors
\n
\n
\n
Mutable Objects
\n
Builder is designed for immutability; doesn’t benefit mutable objects
\n
\n
\n
Performance Critical
\n
Memory overhead of builder may matter in high-frequency scenarios
\n
\n
\n
All Parameters Optional
\n
If no mandatory parameters, builder doesn’t enforce constraints
\n
\n
\n
Frequent Modification
\n
If object needs modification after creation, use setters instead
\n
\n\n
\n\n
⚠️ Common Anti-Patterns & Misuses
\n
\n\n
\n
Anti-Pattern
\n
Problem
\n
Solution
\n
\n\n\n
\n
Shared Builder Across Threads
\n
Race conditions when building concurrent products
\n
Create new builder per thread; builders not thread-safe
\n
\n
\n
Builder Without Validation
\n
Invalid objects created if validation deferred
\n
Implement validation in build() method
\n
\n
\n
All-Optional Builder
\n
No constraints on required parameters
\n
Enforce mandatory params in builder constructor
\n
\n
\n
Complex Directors
\n
Director hides builder complexity instead of simplifying it
\n
Director should orchestrate, not complicate
\n
\n
\n
Mutable Product After Build
\n
Product state modified after construction defeats builder purpose
\n
Keep product immutable; add new builder if changes needed
\n
\n
\n
Builder with Setters
\n
Contradicts immutability goal
\n
Use only fluent builder methods, no setters on product
\n
\n\n
\n\n
🌍 Real-World Use Cases
\n
Java StringBuilder
\n
java
// StringBuilder is a builder for immutable String\nStringtext=newStringBuilder()\n .append("Hello")\n .append(" ")\n .append("World")\n .toString();\n
Google Guava - ImmutableList
\n
java
// Guava uses builder for complex immutable collections\nImmutableList<String> list = ImmutableList.builder()\n .add("item1")\n .add("item2")\n .build();\n
\n",
+ "contentMarkdown": "# Builder Pattern\n\n## 📋 Overview\n\nThe **Builder Pattern** is a creational pattern that constructs complex objects step-by-step, separating the construction logic from the representation. It provides a fluent, readable interface for building objects with many optional parameters or complex initialization logic.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Creating objects with many parameters is error-prone and produces unreadable code\n- Objects have optional and mandatory parameters; telescoping constructors become unwieldy\n- Complex initialization logic should be separated from object representation\n- You need to construct immutable objects while maintaining readability\n\n**Use When:**\n- Objects have 3+ optional parameters\n- You need to build immutable objects with validation\n- Construction logic is complex or multi-step\n- You want to improve code readability over constructor overloading\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| **Product** | The complex object being constructed (e.g., Hero) |\n| **Builder** | Abstract interface defining construction steps |\n| **Concrete Builder** | Implements construction steps, accumulates result |\n| **Director** | (Optional) Orchestrates the builder to construct products in a specific order |\n| **Client** | Uses builder to construct products |\n\n**Key Characteristics:**\n- Fluent interface enabling method chaining\n- Separation of construction from representation\n- Step-by-step object assembly\n- Validation at build stage\n\n---\n\n## 💡 Implementation Example\n\n```java\n// Product: Complex object to build\npublic class Hero {\n private final String name;\n private final Profession profession;\n private final HairType hairType;\n private final HairColor hairColor;\n private final Armor armor;\n private final Weapon weapon;\n\n private Hero(HeroBuilder builder) {\n this.name = builder.name;\n this.profession = builder.profession;\n this.hairType = builder.hairType;\n this.hairColor = builder.hairColor;\n this.armor = builder.armor;\n this.weapon = builder.weapon;\n }\n\n // Builder: Inner class managing construction\n public static class HeroBuilder {\n private final String name;\n private final Profession profession;\n private HairType hairType;\n private HairColor hairColor;\n private Armor armor;\n private Weapon weapon;\n\n // Mandatory parameters in constructor\n public HeroBuilder(Profession profession, String name) {\n this.profession = profession;\n this.name = name;\n }\n\n // Fluent methods for optional parameters\n public HeroBuilder withHairType(HairType hairType) {\n this.hairType = hairType;\n return this;\n }\n\n public HeroBuilder withHairColor(HairColor hairColor) {\n this.hairColor = hairColor;\n return this;\n }\n\n public HeroBuilder withArmor(Armor armor) {\n this.armor = armor;\n return this;\n }\n\n public HeroBuilder withWeapon(Weapon weapon) {\n this.weapon = weapon;\n return this;\n }\n\n // Build: Final step returning the constructed product\n public Hero build() {\n return new Hero(this);\n }\n }\n}\n\n// Usage: Clean, readable, chainable construction\nHero mage = new Hero.HeroBuilder(Profession.MAGE, \"Merlin\")\n .withHairColor(HairColor.BLACK)\n .withWeapon(Weapon.STAFF)\n .build();\n```\n\n**Reasoning:** \n- Separates object construction from its representation\n- Fluent interface improves readability dramatically\n- Mandatory parameters enforced in constructor\n- Optional parameters via fluent methods\n- Immutability achieved through private constructor\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Director {\n -builder: Builder\n +construct()\n }\n class Builder {\n <>\n +buildPartA()\n +buildPartB()\n +getResult()\n }\n class ConcreteBuilder\n class Product\n Client --> Director\n Director --> Builder\n Builder <|-- ConcreteBuilder\n ConcreteBuilder --> Product\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>Director: construct()\n Director->>Builder: buildPartA()\n Director->>Builder: buildPartB()\n Builder-->>Director: done\n Client->>Builder: getResult()\n Builder-->>Client: Product\n```\n\n---\n\n## 🔀 Design Principles Emphasized\n\n| Principle | How Applied |\n|-----------|------------|\n| **Single Responsibility** | Builder manages construction; Product manages data |\n| **Separation of Concerns** | Object representation separated from construction logic |\n| **Composition over Inheritance** | Builder uses composition to accumulate object state |\n| **Fluent Interface** | Method chaining improves readability |\n| **Immutability** | Constructor is private; object state set via builder |\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- **Improved Readability:** Fluent interface makes code self-documenting\n- **Flexibility:** Easy to add/remove optional parameters without breaking code\n- **Immutability:** Separating construction enables creation of immutable objects\n- **Complex Initialization:** Handles multi-step construction elegantly\n- **Mandatory Parameter Enforcement:** Constructor ensures required params are present\n- **Validation:** Can validate at build stage before creating object\n\n### Disadvantages ❌\n- **Code Verbosity:** More classes and methods to maintain\n- **Performance Overhead:** Creating builder object adds memory/GC pressure\n- **Complexity for Simple Objects:** Overkill for objects with few parameters\n- **Thread Safety:** Builder itself is not thread-safe; don't share across threads\n- **Builder Proliferation:** Every complex class needs its own builder\n\n---\n\n## 🚫 When NOT to Use\n\n| Scenario | Why Avoid |\n|----------|-----------|\n| **Simple Objects** | Objects with 1-2 parameters; use direct constructors |\n| **Mutable Objects** | Builder is designed for immutability; doesn't benefit mutable objects |\n| **Performance Critical** | Memory overhead of builder may matter in high-frequency scenarios |\n| **All Parameters Optional** | If no mandatory parameters, builder doesn't enforce constraints |\n| **Frequent Modification** | If object needs modification after creation, use setters instead |\n\n---\n\n## ⚠️ Common Anti-Patterns & Misuses\n\n| Anti-Pattern | Problem | Solution |\n|--------------|---------|----------|\n| **Shared Builder Across Threads** | Race conditions when building concurrent products | Create new builder per thread; builders not thread-safe |\n| **Builder Without Validation** | Invalid objects created if validation deferred | Implement validation in `build()` method |\n| **All-Optional Builder** | No constraints on required parameters | Enforce mandatory params in builder constructor |\n| **Complex Directors** | Director hides builder complexity instead of simplifying it | Director should orchestrate, not complicate |\n| **Mutable Product After Build** | Product state modified after construction defeats builder purpose | Keep product immutable; add new builder if changes needed |\n| **Builder with Setters** | Contradicts immutability goal | Use only fluent builder methods, no setters on product |\n\n---\n\n## 🌍 Real-World Use Cases\n\n### Java StringBuilder\n```java\n// StringBuilder is a builder for immutable String\nString text = new StringBuilder()\n .append(\"Hello\")\n .append(\" \")\n .append(\"World\")\n .toString();\n```\n\n### Google Guava - ImmutableList\n```java\n// Guava uses builder for complex immutable collections\nImmutableList list = ImmutableList.builder()\n .add(\"item1\")\n .add(\"item2\")\n .build();\n```\n\n### Lombok @Builder\n```java\n// Lombok annotation auto-generates builder\n@Builder\npublic class User {\n private String name;\n private String email;\n private int age;\n}\n\n// Usage\nUser user = User.builder()\n .name(\"Alice\")\n .email(\"alice@example.com\")\n .age(30)\n .build();\n```\n\n### HTTP Clients (OkHttp)\n```java\n// OkHttp Request builder\nRequest request = new Request.Builder()\n .url(\"https://example.com\")\n .addHeader(\"User-Agent\", \"MyApp\")\n .post(body)\n .build();\n```\n\n### Apache Commons - Configuration\n```java\n// Configuration builder with fluent interface\nConfiguration config = new Configuration.Builder()\n .setDatabaseUrl(\"jdbc:mysql://localhost\")\n .setMaxConnections(50)\n .setReadTimeout(5000)\n .build();\n```\n\n---\n\n## 🔗 Alternatives & Similar Patterns\n\n| Alternative | When to Prefer |\n|-------------|-----------------|\n| **Telescoping Constructor** | For simple objects with few parameters |\n| **JavaBeans with Setters** | When mutability is acceptable; not ideal for immutability |\n| **Factory Method** | For creating simple objects or choosing implementations |\n| **Abstract Factory** | When building families of related objects |\n| **Fluent Configuration** | Lightweight alternative to builder for configuration objects |\n\n---\n\n## 📝 Best Practices\n\n1. **Enforce Mandatory Parameters:** Place required params in builder constructor\n2. **Use Method Chaining:** Return `this` for fluent interface\n3. **Validate in Build:** Check constraints before creating product\n4. **Keep Builder Simple:** Avoid complex logic; delegate to product\n5. **Consider Lombok:** Use `@Builder` annotation to auto-generate builder code\n6. **Make Product Immutable:** Private constructor, final fields\n7. **Document Optional Parameters:** Clarify defaults and constraints\n8. **Provide Copy Constructor:** Allow building new instance from existing product\n\n---\n\n## 🎓 Related Patterns\n\n- **Factory Pattern:** Can be used within builder to create complex sub-objects\n- **Composite Pattern:** Builder often used to construct composite structures\n- **Strategy Pattern:** Builder can use different strategies for object construction\n- **Template Method:** Builder steps can follow a template structure\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Effective Java (Joshua Bloch) - Item 2: Builder Pattern\n- Google Guava Library\n- Lombok @Builder Annotation",
+ "relatedPatternIds": [
+ "singleton",
+ "abstract-factory",
+ "factory-method",
+ "prototype"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "🔀 Design Principles Emphasized",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns & Misuses",
+ "🌍 Real-World Use Cases",
+ "Java StringBuilder",
+ "Google Guava - ImmutableList",
+ "Lombok @Builder",
+ "HTTP Clients (OkHttp)",
+ "Apache Commons - Configuration",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "🎓 Related Patterns",
+ "📚 References"
+ ],
+ "excerpt": "Builder Pattern 📋 Overview The Builder Pattern is a creational pattern that constructs complex objects step by step, separating the construction logic from the representation. It provides a fluent, readable interface for building objects with many optional pa",
+ "featured": false,
+ "previewImage": "/pattern-previews/builder.svg",
+ "previewThumbnailImage": "/pattern-previews/builder.svg"
+ },
+ {
+ "id": "chain",
+ "slug": "chain",
+ "name": "Chain of Responsibility",
+ "category": "gof",
+ "subcategory": "behavioral",
+ "summary": "The Chain of Responsibility pattern passes a request along a chain of handlers. Each handler decides either to process the request or pass it to the next handler in the chain.",
+ "intent": "The Chain of Responsibility pattern passes a request along a chain of handlers. Each handler decides either to process the request or pass it to the next handler in the chain.",
+ "applicability": [
+ "Simple sequential processing",
+ "One handler always handles the request",
+ "Performance-critical applications",
+ "Clear handler hierarchy exists"
+ ],
+ "advantages": [
+ "Decouples sender from receiver",
+ "Dynamic handler assignment",
+ "Easy to add/remove handlers",
+ "Multiple handlers can process request",
+ "Flexible request handling"
+ ],
+ "disadvantages": [
+ "Request may not be handled",
+ "Debugging difficult with long chains",
+ "Performance impact with many handlers",
+ "Chain configuration complexity",
+ "Potential circular references"
+ ],
+ "tradeOffs": [],
+ "alternatives": [
+ "Simple sequential processing",
+ "One handler always handles the request",
+ "Performance-critical applications",
+ "Clear handler hierarchy exists"
+ ],
+ "keywords": [
+ "Chain of Responsibility",
+ "gof",
+ "behavioral",
+ "chain",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "design principles",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns",
+ "real-world use cases",
+ "best practices",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "🔀 Design Principles",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns",
+ "🌍 Real-World Use Cases",
+ "📝 Best Practices",
+ "📚 References",
+ "The",
+ "Responsibility",
+ "pattern",
+ "passes",
+ "request",
+ "along",
+ "handlers",
+ "Each",
+ "handler",
+ "decides",
+ "either",
+ "process",
+ "pass",
+ "next"
+ ],
+ "aliases": [
+ "chain",
+ "Chain of Responsibility"
+ ],
+ "tags": [
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "design principles",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns",
+ "real-world use cases",
+ "best practices",
+ "references"
+ ],
+ "githubPath": "gof-patterns/chain",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/chain",
+ "demoCodePaths": [
+ "gof-patterns/chain/src/main/java",
+ "gof-patterns/chain/src/main",
+ "gof-patterns/chain/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 2,
+ "contentHtml": "
Chain of Responsibility Pattern
\n
📋 Overview
\n
The Chain of Responsibility pattern passes a request along a chain of handlers. Each handler decides either to process the request or pass it to the next handler in the chain.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
You need to process a request by multiple handlers without knowing which handler will process it in advance
\n
You want to decouple the sender of a request from its receiver
\n
You want to allow adding/removing handlers dynamically
\n
\n
Use When:
\n
\n
Multiple objects may handle a request
\n
You don’t know in advance which object should handle the request
\n
You want to issue a request to multiple handlers without specifying the receiver explicitly
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Handler
\n
Defines interface for handling requests and linking handlers
Reasoning: Decouples sender from receiver; handlers decide whether to handle or pass on request dynamically.
\n\n
🔀 Design Principles
\n
\n
Dependency Inversion Principle
\n
Single Responsibility Principle
\n
Open/Closed Principle
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Client\n class Request\n class Handler {\n <<abstract>>\n -next: Handler\n +setNext(h: Handler)\n +handle(r: Request)\n }\n class ConcreteHandlerA\n class ConcreteHandlerB\n Client --> Handler\n Handler <|-- ConcreteHandlerA\n Handler <|-- ConcreteHandlerB\n Handler --> Handler\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n Client->>HandlerA: handle(request)\n alt canHandle\n HandlerA-->>Client: handled\n else pass\n HandlerA->>HandlerB: handle(request)\n HandlerB-->>Client: handled\n end\n
\n
⚖️ Trade-offs
\n
Advantages ✅
\n
\n
Decouples sender from receiver
\n
Dynamic handler assignment
\n
Easy to add/remove handlers
\n
Multiple handlers can process request
\n
Flexible request handling
\n
\n
Disadvantages ❌
\n
\n
Request may not be handled
\n
Debugging difficult with long chains
\n
Performance impact with many handlers
\n
Chain configuration complexity
\n
Potential circular references
\n
\n\n
🚫 When NOT to Use
\n
\n
Simple sequential processing
\n
One handler always handles the request
\n
Performance-critical applications
\n
Clear handler hierarchy exists
\n
\n\n
⚠️ Common Anti-Patterns
\n
\n\n
\n
Anti-Pattern
\n
Problem
\n
Solution
\n
\n\n\n
\n
Infinite Loops
\n
Circular chain references
\n
Prevent circular chains
\n
\n
\n
Silent Failures
\n
Request disappears without handling
\n
Always handle or log
\n
\n
\n
God Handler
\n
Handler does too much
\n
Split into multiple handlers
\n
\n\n
\n\n
🌍 Real-World Use Cases
\n
\n
Event handling in GUI frameworks
\n
Exception handling in Java
\n
Servlet filters in web frameworks
\n
Logging frameworks with appender chains
\n
Authorization/authentication pipelines
\n
\n\n
📝 Best Practices
\n\n
Define clear handler contract
\n
Document chain behavior
\n
Handle unprocessed requests
\n
Avoid infinite loops in chain
\n
Keep handlers focused
\n
Consider handler ordering
\n
Log at each stage
\n
Provide default handler
\n\n\n
📚 References
\n
\n
Gang of Four Design Patterns
\n
Effective Java (Joshua Bloch)
\n
Design Patterns in Java
\n
\n",
+ "contentMarkdown": "# Chain of Responsibility Pattern\n\n## 📋 Overview\n\nThe **Chain of Responsibility** pattern passes a request along a chain of handlers. Each handler decides either to process the request or pass it to the next handler in the chain.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- You need to process a request by multiple handlers without knowing which handler will process it in advance\n- You want to decouple the sender of a request from its receiver\n- You want to allow adding/removing handlers dynamically\n\n**Use When:**\n- Multiple objects may handle a request\n- You don't know in advance which object should handle the request\n- You want to issue a request to multiple handlers without specifying the receiver explicitly\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| Handler | Defines interface for handling requests and linking handlers |\n| ConcreteHandler | Handles requests or passes them to next handler |\n| Client | Initiates request into the chain |\n\n---\n\n## 💡 Code Example\n\n```java\npublic abstract class RequestHandler {\n protected RequestHandler nextHandler;\n \n public void setNextHandler(RequestHandler nextHandler) {\n this.nextHandler = nextHandler;\n }\n \n public abstract void handleRequest(Request request);\n}\n\npublic class ConcreteHandler extends RequestHandler {\n @Override\n public void handleRequest(Request request) {\n if (canHandle(request)) {\n process(request);\n } else if (nextHandler != null) {\n nextHandler.handleRequest(request);\n }\n }\n \n private boolean canHandle(Request request) {\n return request.getType() == RequestType.TYPE_A;\n }\n \n private void process(Request request) {\n System.out.println(\"Processing request: \" + request);\n }\n}\n\n// Usage\nRequestHandler handler1 = new ConcreteHandler();\nRequestHandler handler2 = new ConcreteHandler();\nhandler1.setNextHandler(handler2);\nhandler1.handleRequest(new Request(RequestType.TYPE_A));\n```\n\n**Reasoning:** Decouples sender from receiver; handlers decide whether to handle or pass on request dynamically.\n\n---\n\n## 🔀 Design Principles\n\n- **Dependency Inversion Principle**\n- **Single Responsibility Principle**\n- **Open/Closed Principle**\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Request\n class Handler {\n <>\n -next: Handler\n +setNext(h: Handler)\n +handle(r: Request)\n }\n class ConcreteHandlerA\n class ConcreteHandlerB\n Client --> Handler\n Handler <|-- ConcreteHandlerA\n Handler <|-- ConcreteHandlerB\n Handler --> Handler\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>HandlerA: handle(request)\n alt canHandle\n HandlerA-->>Client: handled\n else pass\n HandlerA->>HandlerB: handle(request)\n HandlerB-->>Client: handled\n end\n```\n\n---\n\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Decouples sender from receiver\n- Dynamic handler assignment\n- Easy to add/remove handlers\n- Multiple handlers can process request\n- Flexible request handling\n\n### Disadvantages ❌\n- Request may not be handled\n- Debugging difficult with long chains\n- Performance impact with many handlers\n- Chain configuration complexity\n- Potential circular references\n\n---\n\n## 🚫 When NOT to Use\n\n- Simple sequential processing\n- One handler always handles the request\n- Performance-critical applications\n- Clear handler hierarchy exists\n\n---\n\n## ⚠️ Common Anti-Patterns\n\n| Anti-Pattern | Problem | Solution |\n|--------------|---------|----------|\n| Infinite Loops | Circular chain references | Prevent circular chains |\n| Silent Failures | Request disappears without handling | Always handle or log |\n| God Handler | Handler does too much | Split into multiple handlers |\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Event handling in GUI frameworks\n- Exception handling in Java\n- Servlet filters in web frameworks\n- Logging frameworks with appender chains\n- Authorization/authentication pipelines\n\n---\n\n## 📝 Best Practices\n\n1. Define clear handler contract\n2. Document chain behavior\n3. Handle unprocessed requests\n4. Avoid infinite loops in chain\n5. Keep handlers focused\n6. Consider handler ordering\n7. Log at each stage\n8. Provide default handler\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Effective Java (Joshua Bloch)\n- Design Patterns in Java",
+ "relatedPatternIds": [
+ "abstract-factory",
+ "factory-method",
+ "adapter",
+ "bridge"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "🔀 Design Principles",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns",
+ "🌍 Real-World Use Cases",
+ "📝 Best Practices",
+ "📚 References"
+ ],
+ "excerpt": "Chain of Responsibility Pattern 📋 Overview The Chain of Responsibility pattern passes a request along a chain of handlers. Each handler decides either to process the request or pass it to the next handler in the chain. 👥 Roles & Responsibilities Role Respons",
+ "featured": false,
+ "previewImage": "/pattern-previews/chain.svg",
+ "previewThumbnailImage": "/pattern-previews/chain.svg"
+ },
+ {
+ "id": "command",
+ "slug": "command",
+ "name": "Command",
+ "category": "gof",
+ "subcategory": "behavioral",
+ "summary": "The Command pattern encapsulates a request as an object, allowing parameterization of clients with different requests, queuing of requests, and logging of requests.",
+ "intent": "The Command pattern encapsulates a request as an object, allowing parameterization of clients with different requests, queuing of requests, and logging of requests.",
+ "applicability": [],
+ "advantages": [
+ "Decouples invoker from receiver",
+ "Easy to add new commands",
+ "Supports undo/redo",
+ "Can queue commands",
+ "Supports command macros",
+ "Deferred execution"
+ ],
+ "disadvantages": [
+ "More classes required",
+ "Increased memory usage",
+ "Complexity for simple operations",
+ "Undo/redo state management",
+ "Performance overhead"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Command",
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "pattern",
+ "encapsulates",
+ "request",
+ "object",
+ "allowing",
+ "parameterization",
+ "clients",
+ "with",
+ "different",
+ "requests",
+ "queuing",
+ "and",
+ "logging"
+ ],
+ "aliases": [
+ "command"
+ ],
+ "tags": [
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "gof-patterns/command",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/command",
+ "demoCodePaths": [
+ "gof-patterns/command/src/main/java",
+ "gof-patterns/command/src/main",
+ "gof-patterns/command/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Command Pattern
\n
📋 Overview
\n
The Command pattern encapsulates a request as an object, allowing parameterization of clients with different requests, queuing of requests, and logging of requests.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Encapsulate a request as an object
\n
Decouple the object that invokes an operation from the one that performs it
Simple objects with straightforward creation - Use direct instantiation
\n
Single product type - Unnecessary abstraction
\n
Static factory methods sufficient - Use static factories instead
\n
\n\n
⚠️ Common Anti-Patterns
\n
\n\n
\n
Anti-Pattern
\n
Problem
\n
Solution
\n
\n\n\n
\n
Over-Abstracting
\n
Creating factory for every object
\n
Use only when creation logic is complex
\n
\n
\n
Leaky Abstractions
\n
Creator exposes product implementation
\n
Keep abstractions strict
\n
\n
\n
Mixing Responsibilities
\n
Creator also validates/processes
\n
Separate concerns
\n
\n\n
\n\n
🌍 Real-World Use Cases
\n
\n
Java Collections:List.of(), Set.of()
\n
SLF4J:LoggerFactory.getLogger()
\n
JDBC:DriverManager.getConnection()
\n
XML:DocumentBuilderFactory.newInstance()
\n
\n\n
🔗 Alternatives & Similar Patterns
\n
\n\n
\n
Alternative
\n
When to Use
\n
\n\n\n
\n
Abstract Factory
\n
When managing families of related products
\n
\n
\n
Builder
\n
When object construction is complex
\n
\n
\n
Prototype
\n
When cloning is more efficient
\n
\n\n
\n\n
📝 Best Practices
\n\n
Keep factory interface simple and intuitive
\n
Avoid making factory methods do too much
\n
Document expected exceptions
\n
Provide clear naming for factory methods
\n
Consider static factory methods for simplicity
\n
Ensure thread-safety if needed
\n
Validate inputs before creating objects
\n
Provide sensible defaults where possible
\n\n\n
🎓 Related Patterns
\n
\n
Abstract Factory
\n
Builder Pattern
\n
Prototype Pattern
\n
Singleton Pattern
\n
\n\n
📚 References
\n
\n
Gang of Four Design Patterns
\n
Effective Java (Joshua Bloch)
\n
Design Patterns in Java (Edith Freeman et al.)
\n
\n",
+ "contentMarkdown": "# Factory Method Pattern\n\n## 📋 Overview\n\nThe **Factory Method Pattern** defines an interface for creating an object, letting subclasses decide which class to instantiate.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- You need to create objects but don't know the concrete class until runtime\n- You want subclasses to specify the objects they create\n- Object creation logic should be separate from usage\n\n**Use When:**\n- A class cannot anticipate the type of objects it needs to create\n- You want subclasses to specify the objects they create\n- Object creation logic should be separate from business logic\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| Creator | Declares factory method; may provide default implementation |\n| ConcreteCreator | Overrides factory method to create specific product |\n| Product | Declares interface for objects |\n| ConcreteProduct | Implements product interface |\n\n---\n\n## 💡 Code Example\n\n```java\n// Product Interface\npublic interface Transport {\n void deliver(String cargo);\n}\n\n// Concrete Products\npublic class Truck implements Transport {\n @Override\n public void deliver(String cargo) {\n System.out.println(\"Truck delivering: \" + cargo);\n }\n}\n\n// Creator (Abstract)\npublic abstract class Logistics {\n abstract Transport createTransport();\n \n public void planDelivery(String cargo) {\n Transport transport = createTransport();\n transport.deliver(cargo);\n }\n}\n\n// Concrete Creator\npublic class RoadLogistics extends Logistics {\n @Override\n Transport createTransport() {\n return new Truck();\n }\n}\n\n// Usage\nLogistics logistics = new RoadLogistics();\nlogistics.planDelivery(\"Package\");\n```\n\n**Reasoning:** Clients depend on abstractions, not concrete classes. Subclasses decide what product to create. Promotes loose coupling and flexibility.\n\n---\n\n## 🔀 Design Principles\n\n- **Dependency Inversion Principle:** Depend on abstractions\n- **Open/Closed Principle:** New products without modifying Creator\n- **Single Responsibility Principle:** Creator handles only creation logic\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Creator {\n <>\n +factoryMethod(): Product\n +anOperation()\n }\n class ConcreteCreator\n class Product {\n <>\n +use()\n }\n class ConcreteProduct\n Client --> Creator\n Creator <|-- ConcreteCreator\n Product <|-- ConcreteProduct\n Creator --> Product\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>Creator: anOperation()\n Creator->>Creator: factoryMethod()\n Creator->>Product: use()\n Product-->>Creator: result\n Creator-->>Client: result\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Decouples creator from concrete products\n- Encapsulates creation logic\n- Easier to add new product types\n- Cleaner code than multiple if-else branches\n\n### Disadvantages ❌\n- Creates subclass hierarchy just for creation\n- Can be overkill for simple scenarios\n- More complex than direct instantiation\n- Multiple files for simple variations\n\n---\n\n## 🚫 When NOT to Use\n\n- **Simple objects with straightforward creation** - Use direct instantiation\n- **Single product type** - Unnecessary abstraction\n- **Static factory methods sufficient** - Use static factories instead\n\n---\n\n## ⚠️ Common Anti-Patterns\n\n| Anti-Pattern | Problem | Solution |\n|--------------|---------|----------|\n| Over-Abstracting | Creating factory for every object | Use only when creation logic is complex |\n| Leaky Abstractions | Creator exposes product implementation | Keep abstractions strict |\n| Mixing Responsibilities | Creator also validates/processes | Separate concerns |\n\n---\n\n## 🌍 Real-World Use Cases\n\n- **Java Collections:** `List.of()`, `Set.of()`\n- **SLF4J:** `LoggerFactory.getLogger()`\n- **JDBC:** `DriverManager.getConnection()`\n- **XML:** `DocumentBuilderFactory.newInstance()`\n\n---\n\n## 🔗 Alternatives & Similar Patterns\n\n| Alternative | When to Use |\n|-------------|------------|\n| Abstract Factory | When managing families of related products |\n| Builder | When object construction is complex |\n| Prototype | When cloning is more efficient |\n\n---\n\n## 📝 Best Practices\n\n1. Keep factory interface simple and intuitive\n2. Avoid making factory methods do too much\n3. Document expected exceptions\n4. Provide clear naming for factory methods\n5. Consider static factory methods for simplicity\n6. Ensure thread-safety if needed\n7. Validate inputs before creating objects\n8. Provide sensible defaults where possible\n\n---\n\n## 🎓 Related Patterns\n\n- Abstract Factory\n- Builder Pattern\n- Prototype Pattern\n- Singleton Pattern\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Effective Java (Joshua Bloch)\n- Design Patterns in Java (Edith Freeman et al.)",
+ "relatedPatternIds": [
+ "abstract-factory",
+ "builder",
+ "singleton",
+ "prototype"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "🔀 Design Principles",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns",
+ "🌍 Real-World Use Cases",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "🎓 Related Patterns",
+ "📚 References"
+ ],
+ "excerpt": "Factory Method Pattern 📋 Overview The Factory Method Pattern defines an interface for creating an object, letting subclasses decide which class to instantiate. 👥 Roles & Responsibilities Role Responsibility Creator Declares factory method; may provide defaul",
+ "featured": false,
+ "previewImage": "/pattern-previews/factory-method.svg",
+ "previewThumbnailImage": "/pattern-previews/factory-method.svg"
+ },
+ {
+ "id": "flyweight",
+ "slug": "flyweight",
+ "name": "Flyweight",
+ "category": "gof",
+ "subcategory": "structural",
+ "summary": "This folder contains the Flyweight design pattern implementation.",
+ "intent": "This folder contains the Flyweight design pattern implementation.",
+ "applicability": [
+ "For simple scenarios where direct solutions suffice",
+ "When performance is critical and overhead is unacceptable",
+ "In situations where the pattern doesn't naturally fit"
+ ],
+ "advantages": [
+ "Provides structured solution",
+ "Promotes code reusability",
+ "Improves maintainability"
+ ],
+ "disadvantages": [
+ "May add complexity",
+ "Performance overhead",
+ "Learning curve"
+ ],
+ "tradeOffs": [],
+ "alternatives": [
+ "For simple scenarios where direct solutions suffice",
+ "When performance is critical and overhead is unacceptable",
+ "In situations where the pattern doesn't naturally fit"
+ ],
+ "keywords": [
+ "Flyweight",
+ "gof",
+ "structural",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns",
+ "real-world use cases",
+ "alternatives similar patterns",
+ "best practices",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns",
+ "🌍 Real-World Use Cases",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "📚 References",
+ "This",
+ "folder",
+ "contains",
+ "the",
+ "design",
+ "pattern",
+ "implementation"
+ ],
+ "aliases": [
+ "flyweight"
+ ],
+ "tags": [
+ "gof",
+ "structural",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns",
+ "real-world use cases",
+ "alternatives similar patterns",
+ "best practices",
+ "references"
+ ],
+ "githubPath": "gof-patterns/flyweight",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/flyweight",
+ "demoCodePaths": [
+ "gof-patterns/flyweight/src/main/java",
+ "gof-patterns/flyweight/src/main",
+ "gof-patterns/flyweight/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 2,
+ "contentHtml": "
Flyweight Pattern
\n
📋 Overview
\n
This folder contains the Flyweight design pattern implementation.
\n\n
🎯 Intent
\n
The flyweight pattern solves a specific structural or behavioral problem in software design by providing reusable solutions.
\n\n
👥 Roles & Responsibilities
\n
This pattern involves multiple roles working together to achieve separation of concerns and flexibility.
\n\n
💡 Code Example
\n
Please see the src/ directory for complete, executable code examples demonstrating this pattern.
\n\n
📊 Class Diagram
\n
classDiagram\n class Client\n class Flyweight {\n <<interface>>\n +operation(extrinsic)\n }\n class ConcreteFlyweight\n class FlyweightFactory {\n -pool: Map\n +getFlyweight(key)\n }\n Client --> FlyweightFactory\n Flyweight <|-- ConcreteFlyweight\n FlyweightFactory --> Flyweight\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n Client->>FlyweightFactory: getFlyweight(key)\n FlyweightFactory-->>Client: Flyweight\n Client->>Flyweight: operation(extrinsicState)\n
\n
⚖️ Trade-offs
\n
Advantages ✅
\n
\n
Provides structured solution
\n
Promotes code reusability
\n
Improves maintainability
\n
\n
Disadvantages ❌
\n
\n
May add complexity
\n
Performance overhead
\n
Learning curve
\n
\n\n
🚫 When NOT to Use
\n
\n
For simple scenarios where direct solutions suffice
\n
When performance is critical and overhead is unacceptable
\n
In situations where the pattern doesn’t naturally fit
\n
\n\n
⚠️ Common Anti-Patterns
\n
\n\n
\n
Anti-Pattern
\n
Issue
\n
Solution
\n
\n\n\n
\n
Overuse
\n
Using pattern unnecessarily
\n
Apply YAGNI principle
\n
\n
\n
Misapplication
\n
Wrong context for pattern
\n
Study pattern requirements
\n
\n
\n
Complexity
\n
Pattern makes code harder
\n
Simplify or choose different pattern
\n
\n\n
\n\n
🌍 Real-World Use Cases
\n
This pattern appears frequently in:
\n
\n
Enterprise applications
\n
Framework and library design
\n
System integration scenarios
\n
\n\n
🔗 Alternatives & Similar Patterns
\n
\n
Other structural/behavioral patterns
\n
Simpler direct approaches
\n
Complementary patterns
\n
\n\n
📝 Best Practices
\n\n
Understand the problem before applying the pattern
\n
Document your pattern usage clearly
\n
Keep implementations simple
\n
Test thoroughly
\n
Consider performance implications
\n
Review periodically for improvements
\n
Teach team members about the pattern
\n
Refactor if pattern no longer applies
\n\n\n
📚 References
\n
\n
Gang of Four Design Patterns
\n
Effective Java (Joshua Bloch)
\n
Design Patterns in Java
\n
Refactoring Guru
\n
\n
For detailed implementation, see the source files in src/.
\n",
+ "contentMarkdown": "# Flyweight Pattern\n\n## 📋 Overview\n\nThis folder contains the **Flyweight** design pattern implementation.\n\n---\n\n## 🎯 Intent\n\nThe flyweight pattern solves a specific structural or behavioral problem in software design by providing reusable solutions.\n\n---\n\n## 👥 Roles & Responsibilities\n\nThis pattern involves multiple roles working together to achieve separation of concerns and flexibility.\n\n---\n\n## 💡 Code Example\n\nPlease see the `src/` directory for complete, executable code examples demonstrating this pattern.\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Flyweight {\n <>\n +operation(extrinsic)\n }\n class ConcreteFlyweight\n class FlyweightFactory {\n -pool: Map\n +getFlyweight(key)\n }\n Client --> FlyweightFactory\n Flyweight <|-- ConcreteFlyweight\n FlyweightFactory --> Flyweight\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>FlyweightFactory: getFlyweight(key)\n FlyweightFactory-->>Client: Flyweight\n Client->>Flyweight: operation(extrinsicState)\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Provides structured solution\n- Promotes code reusability\n- Improves maintainability\n\n### Disadvantages ❌\n- May add complexity\n- Performance overhead\n- Learning curve\n\n---\n\n## 🚫 When NOT to Use\n\n- For simple scenarios where direct solutions suffice\n- When performance is critical and overhead is unacceptable\n- In situations where the pattern doesn't naturally fit\n\n---\n\n## ⚠️ Common Anti-Patterns\n\n| Anti-Pattern | Issue | Solution |\n|--------------|-------|----------|\n| Overuse | Using pattern unnecessarily | Apply YAGNI principle |\n| Misapplication | Wrong context for pattern | Study pattern requirements |\n| Complexity | Pattern makes code harder | Simplify or choose different pattern |\n\n---\n\n## 🌍 Real-World Use Cases\n\nThis pattern appears frequently in:\n- Enterprise applications\n- Framework and library design\n- System integration scenarios\n\n---\n\n## 🔗 Alternatives & Similar Patterns\n\n- Other structural/behavioral patterns\n- Simpler direct approaches\n- Complementary patterns\n\n---\n\n## 📝 Best Practices\n\n1. Understand the problem before applying the pattern\n2. Document your pattern usage clearly\n3. Keep implementations simple\n4. Test thoroughly\n5. Consider performance implications\n6. Review periodically for improvements\n7. Teach team members about the pattern\n8. Refactor if pattern no longer applies\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Effective Java (Joshua Bloch)\n- Design Patterns in Java\n- Refactoring Guru\n\nFor detailed implementation, see the source files in `src/`.",
+ "relatedPatternIds": [
+ "adapter",
+ "bridge",
+ "composite",
+ "decorator"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns",
+ "🌍 Real-World Use Cases",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "📚 References"
+ ],
+ "excerpt": "Flyweight Pattern 📋 Overview This folder contains the Flyweight design pattern implementation. 👥 Roles & Responsibilities This pattern involves multiple roles working together to achieve separation of concerns and flexibility. 💡 Code Example Please see the ",
+ "featured": false,
+ "previewImage": "/pattern-previews/flyweight.svg",
+ "previewThumbnailImage": "/pattern-previews/flyweight.svg"
+ },
+ {
+ "id": "interpreter",
+ "slug": "interpreter",
+ "name": "Interpreter",
+ "category": "gof",
+ "subcategory": "behavioral",
+ "summary": "The Interpreter pattern defines a grammatical representation for a language and an interpreter to interpret sentences in that language.",
+ "intent": "The Interpreter pattern defines a grammatical representation for a language and an interpreter to interpret sentences in that language.",
+ "applicability": [],
+ "advantages": [
+ "Easy to modify grammar",
+ "Grammar in code form",
+ "Extensible expressions",
+ "Recursive evaluation",
+ "Natural language representation"
+ ],
+ "disadvantages": [
+ "Complex for large grammars",
+ "Performance overhead",
+ "Many classes required",
+ "Difficult to parse",
+ "Memory consumption"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Interpreter",
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "pattern",
+ "defines",
+ "grammatical",
+ "representation",
+ "for",
+ "language",
+ "and",
+ "interpret",
+ "sentences",
+ "that"
+ ],
+ "aliases": [
+ "interpreter"
+ ],
+ "tags": [
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "gof-patterns/interpreter",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/interpreter",
+ "demoCodePaths": [
+ "gof-patterns/interpreter/src/main/java",
+ "gof-patterns/interpreter/src/main",
+ "gof-patterns/interpreter/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Interpreter Pattern
\n
📋 Overview
\n
The Interpreter pattern defines a grammatical representation for a language and an interpreter to interpret sentences in that language.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Define grammar for domain-specific language
\n
Parse and execute expressions
\n
Build abstract syntax trees
\n
Evaluate language sentences
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
AbstractExpression
\n
Defines interpret interface
\n
\n
\n
TerminalExpression
\n
Implements primitive expressions
\n
\n
\n
NonTerminalExpression
\n
Implements composite expressions
\n
\n
\n
Context
\n
Global information for interpreter
\n
\n\n
\n\n
💡 Implementation
\n
\n
Grammar defined by class hierarchy
\n
Each expression type is a class
\n
interpret() evaluates expression
\n
Recursive interpretation of tree
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Client\n class Context\n class AbstractExpression {\n <<interface>>\n +interpret(ctx: Context)\n }\n class TerminalExpression\n class NonterminalExpression {\n -left: AbstractExpression\n -right: AbstractExpression\n }\n Client --> AbstractExpression\n AbstractExpression <|-- TerminalExpression\n AbstractExpression <|-- NonterminalExpression\n AbstractExpression --> Context\n NonterminalExpression --> AbstractExpression\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n Client->>AbstractExpression: interpret(context)\n AbstractExpression->>AbstractExpression: interpret(child)\n AbstractExpression-->>Client: result\n
\n
⚖️ Trade-offs
\n
Advantages ✅
\n
\n
Easy to modify grammar
\n
Grammar in code form
\n
Extensible expressions
\n
Recursive evaluation
\n
Natural language representation
\n
\n
Disadvantages ❌
\n
\n
Complex for large grammars
\n
Performance overhead
\n
Many classes required
\n
Difficult to parse
\n
Memory consumption
\n
\n\n
🌍 Real-World Use Cases
\n
\n
Expression evaluators
\n
DSL (Domain-Specific Language) implementation
\n
SQL query processing
\n
Regular expression engines
\n
Configuration file parsing
\n
\n\n
📚 References
\n
\n
Gang of Four Design Patterns
\n
Language design patterns
\n
\n",
+ "contentMarkdown": "# Interpreter Pattern\n\n## 📋 Overview\n\nThe **Interpreter** pattern defines a grammatical representation for a language and an interpreter to interpret sentences in that language.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Define grammar for domain-specific language\n- Parse and execute expressions\n- Build abstract syntax trees\n- Evaluate language sentences\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| AbstractExpression | Defines interpret interface |\n| TerminalExpression | Implements primitive expressions |\n| NonTerminalExpression | Implements composite expressions |\n| Context | Global information for interpreter |\n\n---\n\n## 💡 Implementation\n\n- Grammar defined by class hierarchy\n- Each expression type is a class\n- interpret() evaluates expression\n- Recursive interpretation of tree\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Context\n class AbstractExpression {\n <>\n +interpret(ctx: Context)\n }\n class TerminalExpression\n class NonterminalExpression {\n -left: AbstractExpression\n -right: AbstractExpression\n }\n Client --> AbstractExpression\n AbstractExpression <|-- TerminalExpression\n AbstractExpression <|-- NonterminalExpression\n AbstractExpression --> Context\n NonterminalExpression --> AbstractExpression\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>AbstractExpression: interpret(context)\n AbstractExpression->>AbstractExpression: interpret(child)\n AbstractExpression-->>Client: result\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Easy to modify grammar\n- Grammar in code form\n- Extensible expressions\n- Recursive evaluation\n- Natural language representation\n\n### Disadvantages ❌\n- Complex for large grammars\n- Performance overhead\n- Many classes required\n- Difficult to parse\n- Memory consumption\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Expression evaluators\n- DSL (Domain-Specific Language) implementation\n- SQL query processing\n- Regular expression engines\n- Configuration file parsing\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Language design patterns",
+ "relatedPatternIds": [
+ "mediator",
+ "iterator",
+ "memento",
+ "visitor"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Interpreter Pattern 📋 Overview The Interpreter pattern defines a grammatical representation for a language and an interpreter to interpret sentences in that language. 👥 Roles & Responsibilities Role Responsibility AbstractExpression Defines interpret interfa",
+ "featured": false,
+ "previewImage": "/pattern-previews/interpreter.svg",
+ "previewThumbnailImage": "/pattern-previews/interpreter.svg"
+ },
+ {
+ "id": "iterator",
+ "slug": "iterator",
+ "name": "Iterator",
+ "category": "gof",
+ "subcategory": "behavioral",
+ "summary": "The Iterator pattern provides a way to access elements of a collection sequentially without exposing its underlying representation.",
+ "intent": "The Iterator pattern provides a way to access elements of a collection sequentially without exposing its underlying representation.",
+ "applicability": [],
+ "advantages": [
+ "Uniform traversal interface",
+ "Hides collection structure",
+ "Supports multiple iterations",
+ "Decouples collection from traversal",
+ "Different iteration strategies"
+ ],
+ "disadvantages": [
+ "Additional complexity",
+ "Iterator overhead",
+ "State management in iterator",
+ "Concurrent modification issues",
+ "Performance impact"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Iterator",
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "pattern",
+ "provides",
+ "way",
+ "access",
+ "elements",
+ "collection",
+ "sequentially",
+ "without",
+ "exposing",
+ "its",
+ "underlying",
+ "representation"
+ ],
+ "aliases": [
+ "iterator"
+ ],
+ "tags": [
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "gof-patterns/iterator",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/iterator",
+ "demoCodePaths": [
+ "gof-patterns/iterator/src/main/java",
+ "gof-patterns/iterator/src/main",
+ "gof-patterns/iterator/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Iterator Pattern
\n
📋 Overview
\n
The Iterator pattern provides a way to access elements of a collection sequentially without exposing its underlying representation.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Access collection elements without exposing structure
\n
Support multiple simultaneous traversals
\n
Provide uniform interface for different collections
\n
Hide collection implementation details
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Iterator
\n
Defines interface for traversal
\n
\n
\n
ConcreteIterator
\n
Implements traversal logic
\n
\n
\n
Collection
\n
Defines interface for creating iterator
\n
\n
\n
ConcreteCollection
\n
Returns ConcreteIterator
\n
\n\n
\n\n
💡 Implementation
\n
Java’s Iterator interface:
\n
\n
hasNext(): Check if more elements
\n
next(): Get next element
\n
remove(): Remove current element
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Client\n class Iterator {\n <<interface>>\n +hasNext()\n +next()\n }\n class ConcreteIterator\n class Aggregate {\n <<interface>>\n +createIterator(): Iterator\n }\n class ConcreteAggregate\n Client --> Aggregate\n Aggregate <|-- ConcreteAggregate\n Iterator <|-- ConcreteIterator\n ConcreteAggregate --> ConcreteIterator\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n Client->>Aggregate: createIterator()\n Aggregate-->>Client: Iterator\n loop until done\n Client->>Iterator: hasNext()\n Client->>Iterator: next()\n end\n
\n
⚖️ Trade-offs
\n
Advantages ✅
\n
\n
Uniform traversal interface
\n
Hides collection structure
\n
Supports multiple iterations
\n
Decouples collection from traversal
\n
Different iteration strategies
\n
\n
Disadvantages ❌
\n
\n
Additional complexity
\n
Iterator overhead
\n
State management in iterator
\n
Concurrent modification issues
\n
Performance impact
\n
\n\n
🌍 Real-World Use Cases
\n
\n
Java Collections Framework
\n
Database result set traversal
\n
File system traversal
\n
Tree/graph traversal
\n
Stream processing
\n
\n\n
📚 References
\n
\n
Gang of Four Design Patterns
\n
Java Collections Framework
\n
Iterator design
\n
\n",
+ "contentMarkdown": "# Iterator Pattern\n\n## 📋 Overview\n\nThe **Iterator** pattern provides a way to access elements of a collection sequentially without exposing its underlying representation.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Access collection elements without exposing structure\n- Support multiple simultaneous traversals\n- Provide uniform interface for different collections\n- Hide collection implementation details\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| Iterator | Defines interface for traversal |\n| ConcreteIterator | Implements traversal logic |\n| Collection | Defines interface for creating iterator |\n| ConcreteCollection | Returns ConcreteIterator |\n\n---\n\n## 💡 Implementation\n\nJava's Iterator interface:\n- hasNext(): Check if more elements\n- next(): Get next element\n- remove(): Remove current element\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Iterator {\n <>\n +hasNext()\n +next()\n }\n class ConcreteIterator\n class Aggregate {\n <>\n +createIterator(): Iterator\n }\n class ConcreteAggregate\n Client --> Aggregate\n Aggregate <|-- ConcreteAggregate\n Iterator <|-- ConcreteIterator\n ConcreteAggregate --> ConcreteIterator\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>Aggregate: createIterator()\n Aggregate-->>Client: Iterator\n loop until done\n Client->>Iterator: hasNext()\n Client->>Iterator: next()\n end\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Uniform traversal interface\n- Hides collection structure\n- Supports multiple iterations\n- Decouples collection from traversal\n- Different iteration strategies\n\n### Disadvantages ❌\n- Additional complexity\n- Iterator overhead\n- State management in iterator\n- Concurrent modification issues\n- Performance impact\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Java Collections Framework\n- Database result set traversal\n- File system traversal\n- Tree/graph traversal\n- Stream processing\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Java Collections Framework\n- Iterator design",
+ "relatedPatternIds": [
+ "visitor",
+ "interpreter",
+ "memento",
+ "mediator"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Iterator Pattern 📋 Overview The Iterator pattern provides a way to access elements of a collection sequentially without exposing its underlying representation. 👥 Roles & Responsibilities Role Responsibility Iterator Defines interface for traversal ConcreteIt",
+ "featured": false,
+ "previewImage": "/pattern-previews/iterator.svg",
+ "previewThumbnailImage": "/pattern-previews/iterator.svg"
+ },
+ {
+ "id": "mediator",
+ "slug": "mediator",
+ "name": "Mediator",
+ "category": "gof",
+ "subcategory": "behavioral",
+ "summary": "The Mediator pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently.",
+ "intent": "The Mediator pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently.",
+ "applicability": [],
+ "advantages": [
+ "Decouples colleagues",
+ "Centrali"
+ ],
+ "disadvantages": [
+ "Mediator complexity",
+ "God Object risk",
+ "Performance overhead",
+ "Debugging difficulty",
+ "Hidden dependencies"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Mediator",
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "pattern",
+ "defines",
+ "object",
+ "that",
+ "encapsulates",
+ "how",
+ "set",
+ "objects",
+ "interact",
+ "promotes",
+ "loose",
+ "coupling",
+ "keeping",
+ "from",
+ "referring",
+ "each",
+ "other",
+ "explicitly",
+ "and",
+ "lets",
+ "you",
+ "vary",
+ "their",
+ "interaction",
+ "independently"
+ ],
+ "aliases": [
+ "mediator"
+ ],
+ "tags": [
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "gof-patterns/mediator",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/mediator",
+ "demoCodePaths": [
+ "gof-patterns/mediator/src/main/java",
+ "gof-patterns/mediator/src/main",
+ "gof-patterns/mediator/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Mediator Pattern
\n
📋 Overview
\n
The Mediator pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Objects communicate in complex ways
\n
Direct references create tight coupling
\n
Communication logic scattered across classes
\n
Adding new interaction types requires modifications
\n",
+ "contentMarkdown": "# Mediator Pattern\n\n## 📋 Overview\n\nThe **Mediator** pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Objects communicate in complex ways\n- Direct references create tight coupling\n- Communication logic scattered across classes\n- Adding new interaction types requires modifications\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| Mediator | Defines interface for communication |\n| ConcreteMediator | Implements interaction logic |\n| Colleague | Communicates only with mediator |\n- ConcreteColleague | Implements colleague behavior |\n\n---\n\n## 💡 Implementation\n\n- Colleagues reference mediator\n- Mediator knows all colleagues\n- Communication routed through mediator\n- Mediator implements distribution logic\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Mediator {\n <>\n +notify(sender, event)\n }\n class ConcreteMediator\n class Colleague {\n -mediator: Mediator\n +send(event)\n }\n class ColleagueA\n class ColleagueB\n Mediator <|-- ConcreteMediator\n Colleague <|-- ColleagueA\n Colleague <|-- ColleagueB\n Colleague --> Mediator\n ConcreteMediator --> ColleagueA\n ConcreteMediator --> ColleagueB\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n participant ColleagueA\n participant Mediator\n participant ColleagueB\n ColleagueA->>Mediator: notify(A, event)\n Mediator->>ColleagueB: receive(event)\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Decouples colleagues\n- Centralizes control\n- Easy to modify interactions\n- Simplifies colleague classes\n- Reusable colleagues\n\n### Disadvantages ❌\n- Mediator complexity\n- God Object risk\n- Performance overhead\n- Debugging difficulty\n- Hidden dependencies\n\n---\n\n## 🌍 Real-World Use Cases\n\n- ChatRoom mediator\n- Dialog box coordinators\n- Air traffic control\n- Central event dispatcher\n- Workflow engines\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Coordination patterns",
+ "relatedPatternIds": [
+ "interpreter",
+ "visitor",
+ "memento",
+ "observer"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Mediator Pattern 📋 Overview The Mediator pattern defines an object that encapsulates how a set of objects interact. It promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently. 👥 Ro",
+ "featured": false,
+ "previewImage": "/pattern-previews/mediator.svg",
+ "previewThumbnailImage": "/pattern-previews/mediator.svg"
+ },
+ {
+ "id": "memento",
+ "slug": "memento",
+ "name": "Memento",
+ "category": "gof",
+ "subcategory": "behavioral",
+ "summary": "The Memento pattern captures and externalizes an object's internal state without violating encapsulation, and allows the object to be restored to this state later.",
+ "intent": "The Memento pattern captures and externalizes an object's internal state without violating encapsulation, and allows the object to be restored to this state later.",
+ "applicability": [],
+ "advantages": [
+ "Encapsulation preserved",
+ "Simple undo/redo",
+ "State history management",
+ "Seriali"
+ ],
+ "disadvantages": [
+ "Memory overhead",
+ "Performance cost for large objects",
+ "Seriali"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Memento",
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "pattern",
+ "captures",
+ "and",
+ "externalizes",
+ "object",
+ "internal",
+ "state",
+ "without",
+ "violating",
+ "encapsulation",
+ "allows",
+ "restored",
+ "this",
+ "later"
+ ],
+ "aliases": [
+ "memento"
+ ],
+ "tags": [
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "gof-patterns/memento",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/memento",
+ "demoCodePaths": [
+ "gof-patterns/memento/src/main/java",
+ "gof-patterns/memento/src/main",
+ "gof-patterns/memento/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Memento Pattern
\n
📋 Overview
\n
The Memento pattern captures and externalizes an object’s internal state without violating encapsulation, and allows the object to be restored to this state later.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Save and restore object state
\n
Implement undo/redo functionality
\n
Without exposing internal structure
\n
Without violating encapsulation
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Originator
\n
Creates memento, uses memento to restore state
\n
\n
\n
Memento
\n
Stores state snapshot
\n
\n
\n
Caretaker
\n
Manages mementos
\n
\n\n
\n\n
💡 Implementation
\n
\n
Memento stores state snapshot
\n
Originator creates/uses mementos
\n
Caretaker manages memento collection
\n
Enables state history management
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Client\n class Originator {\n +createMemento(): Memento\n +restore(m: Memento)\n }\n class Memento\n class Caretaker {\n -history: List<Memento>\n }\n Client --> Originator\n Client --> Caretaker\n Originator --> Memento\n Caretaker --> Memento\n
\n",
+ "contentMarkdown": "# Memento Pattern\n\n## 📋 Overview\n\nThe **Memento** pattern captures and externalizes an object's internal state without violating encapsulation, and allows the object to be restored to this state later.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Save and restore object state\n- Implement undo/redo functionality\n- Without exposing internal structure\n- Without violating encapsulation\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| Originator | Creates memento, uses memento to restore state |\n| Memento | Stores state snapshot |\n| Caretaker | Manages mementos |\n\n---\n\n## 💡 Implementation\n\n- Memento stores state snapshot\n- Originator creates/uses mementos\n- Caretaker manages memento collection\n- Enables state history management\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Originator {\n +createMemento(): Memento\n +restore(m: Memento)\n }\n class Memento\n class Caretaker {\n -history: List\n }\n Client --> Originator\n Client --> Caretaker\n Originator --> Memento\n Caretaker --> Memento\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>Originator: createMemento()\n Originator-->>Client: Memento\n Client->>Caretaker: store(memento)\n Client->>Originator: restore(memento)\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Encapsulation preserved\n- Simple undo/redo\n- State history management\n- Serialization support\n- Snapshot capability\n\n### Disadvantages ❌\n- Memory overhead\n- Performance cost for large objects\n- Serialization complexity\n- State consistency management\n- Storage requirements\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Text editor undo/redo\n- Database transactions\n- Game state saves\n- Configuration snapshots\n- Version control systems\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- State management patterns",
+ "relatedPatternIds": [
+ "mediator",
+ "visitor",
+ "interpreter",
+ "iterator"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Memento Pattern 📋 Overview The Memento pattern captures and externalizes an object's internal state without violating encapsulation, and allows the object to be restored to this state later. 👥 Roles & Responsibilities Role Responsibility Originator Creates m",
+ "featured": false,
+ "previewImage": "/pattern-previews/memento.svg",
+ "previewThumbnailImage": "/pattern-previews/memento.svg"
+ },
+ {
+ "id": "observer",
+ "slug": "observer",
+ "name": "Observer",
+ "category": "gof",
+ "subcategory": "behavioral",
+ "summary": "The Observer pattern defines a one to many dependency between objects so that when one object changes state, all its dependents are notified automatically.",
+ "intent": "The Observer pattern defines a one to many dependency between objects so that when one object changes state, all its dependents are notified automatically.",
+ "applicability": [],
+ "advantages": [
+ "Loose coupling",
+ "Dynamic observer management",
+ "Supports broadcast communications",
+ "Natural event handling",
+ "Promotes reactive programming"
+ ],
+ "disadvantages": [
+ "Observer ordering unpredictable",
+ "Memory overhead (observer references)",
+ "Performance impact with many observers",
+ "Difficult to trace event flow",
+ "Can lead to memory leaks"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Observer",
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "pattern",
+ "defines",
+ "one",
+ "many",
+ "dependency",
+ "between",
+ "objects",
+ "that",
+ "when",
+ "object",
+ "changes",
+ "state",
+ "all",
+ "its",
+ "dependents",
+ "are",
+ "notified",
+ "automatically",
+ "event-driven",
+ "pub-sub"
+ ],
+ "aliases": [
+ "observer"
+ ],
+ "tags": [
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "gof-patterns/observer",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/observer",
+ "demoCodePaths": [
+ "gof-patterns/observer/src/main/java",
+ "gof-patterns/observer/src/main",
+ "gof-patterns/observer/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Observer Pattern
\n
📋 Overview
\n
The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
An object’s state changes and other objects need to be notified
\n
Notify multiple objects without tight coupling
\n
Enable event-driven architecture
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Subject
\n
Knows observers, provides interface to attach/detach
For simple scenarios where direct solutions suffice
\n
When performance is critical and overhead is unacceptable
\n
In situations where the pattern doesn’t naturally fit
\n
\n\n
⚠️ Common Anti-Patterns
\n
\n\n
\n
Anti-Pattern
\n
Issue
\n
Solution
\n
\n\n\n
\n
Overuse
\n
Using pattern unnecessarily
\n
Apply YAGNI principle
\n
\n
\n
Misapplication
\n
Wrong context for pattern
\n
Study pattern requirements
\n
\n
\n
Complexity
\n
Pattern makes code harder
\n
Simplify or choose different pattern
\n
\n\n
\n\n
🌍 Real-World Use Cases
\n
This pattern appears frequently in:
\n
\n
Enterprise applications
\n
Framework and library design
\n
System integration scenarios
\n
\n\n
🔗 Alternatives & Similar Patterns
\n
\n
Other structural/behavioral patterns
\n
Simpler direct approaches
\n
Complementary patterns
\n
\n\n
📝 Best Practices
\n\n
Understand the problem before applying the pattern
\n
Document your pattern usage clearly
\n
Keep implementations simple
\n
Test thoroughly
\n
Consider performance implications
\n
Review periodically for improvements
\n
Teach team members about the pattern
\n
Refactor if pattern no longer applies
\n\n\n
📚 References
\n
\n
Gang of Four Design Patterns
\n
Effective Java (Joshua Bloch)
\n
Design Patterns in Java
\n
Refactoring Guru
\n
\n
For detailed implementation, see the source files in src/.
\n",
+ "contentMarkdown": "# Proxy Pattern\n\n## 📋 Overview\n\nThis folder contains the **Proxy** design pattern implementation.\n\n---\n\n## 🎯 Intent\n\nThe proxy pattern solves a specific structural or behavioral problem in software design by providing reusable solutions.\n\n---\n\n## 👥 Roles & Responsibilities\n\nThis pattern involves multiple roles working together to achieve separation of concerns and flexibility.\n\n---\n\n## 💡 Code Example\n\nPlease see the `src/` directory for complete, executable code examples demonstrating this pattern.\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Subject {\n <>\n +request()\n }\n class RealSubject\n class Proxy {\n -real: RealSubject\n +request()\n }\n Client --> Subject\n Subject <|-- RealSubject\n Subject <|-- Proxy\n Proxy --> RealSubject\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>Proxy: request()\n Proxy->>RealSubject: request()\n RealSubject-->>Proxy: result\n Proxy-->>Client: result\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Provides structured solution\n- Promotes code reusability\n- Improves maintainability\n\n### Disadvantages ❌\n- May add complexity\n- Performance overhead\n- Learning curve\n\n---\n\n## 🚫 When NOT to Use\n\n- For simple scenarios where direct solutions suffice\n- When performance is critical and overhead is unacceptable\n- In situations where the pattern doesn't naturally fit\n\n---\n\n## ⚠️ Common Anti-Patterns\n\n| Anti-Pattern | Issue | Solution |\n|--------------|-------|----------|\n| Overuse | Using pattern unnecessarily | Apply YAGNI principle |\n| Misapplication | Wrong context for pattern | Study pattern requirements |\n| Complexity | Pattern makes code harder | Simplify or choose different pattern |\n\n---\n\n## 🌍 Real-World Use Cases\n\nThis pattern appears frequently in:\n- Enterprise applications\n- Framework and library design\n- System integration scenarios\n\n---\n\n## 🔗 Alternatives & Similar Patterns\n\n- Other structural/behavioral patterns\n- Simpler direct approaches\n- Complementary patterns\n\n---\n\n## 📝 Best Practices\n\n1. Understand the problem before applying the pattern\n2. Document your pattern usage clearly\n3. Keep implementations simple\n4. Test thoroughly\n5. Consider performance implications\n6. Review periodically for improvements\n7. Teach team members about the pattern\n8. Refactor if pattern no longer applies\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Effective Java (Joshua Bloch)\n- Design Patterns in Java\n- Refactoring Guru\n\nFor detailed implementation, see the source files in `src/`.",
+ "relatedPatternIds": [
+ "adapter",
+ "bridge",
+ "composite",
+ "decorator"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns",
+ "🌍 Real-World Use Cases",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "📚 References"
+ ],
+ "excerpt": "Proxy Pattern 📋 Overview This folder contains the Proxy design pattern implementation. 👥 Roles & Responsibilities This pattern involves multiple roles working together to achieve separation of concerns and flexibility. 💡 Code Example Please see the src/ dir",
+ "featured": false,
+ "previewImage": "/pattern-previews/proxy.svg",
+ "previewThumbnailImage": "/pattern-previews/proxy.svg"
+ },
+ {
+ "id": "singleton",
+ "slug": "singleton",
+ "name": "Singleton",
+ "category": "gof",
+ "subcategory": "creational",
+ "summary": "The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. This is a creational pattern that restricts object instantiation to a single instance while providing a mechanism to access that instance universally.",
+ "intent": "The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. This is a creational pattern that restricts object instantiation to a single instance while providing a mechanism to access that instance universally.",
+ "applicability": [
+ "Scenario Why Avoid Stateful Objects Sharing state across all clients leads to unexpected side effects Testable Systems Global dependencies make unit testing extremely difficult Multiple Instances Needed If business logic later requires multiple instances, refactoring is painful Distributed Systems Each JVM/process gets its own instance",
+ "doesn't guarantee global uniqueness Simple Services Dependency Injection (DI) containers provide same benefits with better flexibility"
+ ],
+ "advantages": [
+ "**Global Access:** Provides easy, centrali"
+ ],
+ "disadvantages": [
+ "**Testing Difficulty:** Hard to mock for unit tests; global state complicates testing",
+ "**Hidden Dependencies:** Not obvious that code depends on a singleton; dependencies are implicit",
+ "**Synchroni"
+ ],
+ "tradeOffs": [],
+ "alternatives": [
+ "Scenario Why Avoid Stateful Objects Sharing state across all clients leads to unexpected side effects Testable Systems Global dependencies make unit testing extremely difficult Multiple Instances Needed If business logic later requires multiple instances, refactoring is painful Distributed Systems Each JVM/process gets its own instance",
+ "doesn't guarantee global uniqueness Simple Services Dependency Injection (DI) containers provide same benefits with better flexibility"
+ ],
+ "keywords": [
+ "Singleton",
+ "gof",
+ "creational",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation strategies",
+ "1 eager initialization",
+ "2 lazy initialization with synchronization",
+ "3 double-checked locking",
+ "4 bill pugh singleton class loader",
+ "class diagram",
+ "sequence diagram",
+ "design principles emphasized",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns misuses",
+ "real-world use cases",
+ "spring framework",
+ "log4j / slf4j",
+ "database connection pool",
+ "configuration manager",
+ "alternatives similar patterns",
+ "best practices",
+ "related patterns",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation Strategies",
+ "1. **Eager Initialization**",
+ "2. **Lazy Initialization with Synchronization**",
+ "3. **Double-Checked Locking**",
+ "4. **Bill Pugh Singleton (Class Loader)**",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "🔀 Design Principles Emphasized",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns & Misuses",
+ "🌍 Real-World Use Cases",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "🎓 Related Patterns",
+ "📚 References",
+ "The",
+ "Pattern",
+ "ensures",
+ "that",
+ "class",
+ "has",
+ "only",
+ "one",
+ "instance",
+ "and",
+ "provides",
+ "global",
+ "point",
+ "access",
+ "This",
+ "restricts",
+ "object",
+ "instantiation",
+ "single",
+ "while",
+ "providing",
+ "mechanism",
+ "universally"
+ ],
+ "aliases": [
+ "singleton"
+ ],
+ "tags": [
+ "gof",
+ "creational",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation strategies",
+ "1 eager initialization",
+ "2 lazy initialization with synchronization",
+ "3 double-checked locking",
+ "4 bill pugh singleton class loader",
+ "class diagram",
+ "sequence diagram",
+ "design principles emphasized",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "common anti-patterns misuses",
+ "real-world use cases",
+ "spring framework",
+ "log4j / slf4j",
+ "database connection pool",
+ "configuration manager",
+ "alternatives similar patterns",
+ "best practices",
+ "related patterns",
+ "references"
+ ],
+ "githubPath": "gof-patterns/singleton",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/singleton",
+ "demoCodePaths": [
+ "gof-patterns/singleton/src/main/java",
+ "gof-patterns/singleton/src/main",
+ "gof-patterns/singleton/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 5,
+ "contentHtml": "
Singleton Pattern
\n
📋 Overview
\n
The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. This is a creational pattern that restricts object instantiation to a single instance while providing a mechanism to access that instance universally.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
You need to guarantee that only one instance of a class exists throughout the application lifecycle
\n
Multiple instances would cause logical errors or resource conflicts (e.g., database connections, configuration managers, logging services)
\n
You need a globally accessible point of access to this single instance without passing references through all layers
\n
\n
Use When:
\n
\n
You need a single, shared resource manager (connection pools, thread pools, caches)
\n
You need a centralized configuration holder or registry
\n
You need exactly one instance of a service to coordinate system-wide activities
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Singleton
\n
Ensures only one instance exists via private constructor; provides static method to access the single instance
\n
\n
\n
Client
\n
Accesses the singleton instance through the public static accessor method
Violates Single Responsibility: Often handles both instantiation and business logic
\n
Rigid: Extending or replacing the singleton is difficult without modifying client code
\n
Global State: Makes code less predictable and harder to reason about
\n
Concurrency Issues: Some implementations (eager loading) may fail under specific multi-threaded scenarios
\n
\n\n
🚫 When NOT to Use
\n
\n\n
\n
Scenario
\n
Why Avoid
\n
\n\n\n
\n
Stateful Objects
\n
Sharing state across all clients leads to unexpected side effects
\n
\n
\n
Testable Systems
\n
Global dependencies make unit testing extremely difficult
\n
\n
\n
Multiple Instances Needed
\n
If business logic later requires multiple instances, refactoring is painful
\n
\n
\n
Distributed Systems
\n
Each JVM/process gets its own instance; doesn’t guarantee global uniqueness
\n
\n
\n
Simple Services
\n
Dependency Injection (DI) containers provide same benefits with better flexibility
\n
\n\n
\n\n
⚠️ Common Anti-Patterns & Misuses
\n
\n\n
\n
Anti-Pattern
\n
Problem
\n
Solution
\n
\n\n\n
\n
Mutable Singleton
\n
Shared state gets corrupted by concurrent modifications
\n
Make singleton immutable or use thread-safe collections
\n
\n
\n
Singleton as Service Locator
\n
Hides dependencies and couples code to singleton
\n
Use constructor injection instead
\n
\n
\n
Testing Without Mock/Spy
\n
Tests affect each other via shared state
\n
Provide reset method or use test-specific implementations
\n
\n
\n
Singleton Inheritance
\n
Each subclass becomes a different singleton
\n
Use composition; wrap the actual singleton
\n
\n
\n
Unnecessary Singletons
\n
Over-use creates tight coupling
\n
Prefer dependency injection via constructors
\n
\n
\n
Non-Thread-Safe Singleton
\n
Race conditions in multi-threaded apps
\n
Use double-checked locking or eager initialization
\n
\n\n
\n\n
🌍 Real-World Use Cases
\n
Spring Framework
\n
java
// Spring beans are singletons by default\n@Service\npublicclassUserService {\n // Only one instance in Spring Container\n}\n\n// Access via Dependency Injection\n@Component\npublicclassUserController {\n @Autowired\n private UserService userService; // Singleton instance injected\n}\n
Log4j / SLF4J
\n
java
// Logger is typically a singleton\nLoggerlogger= LoggerFactory.getLogger(MyClass.class);\n// Returns same logger instance for same class name\n
Database Connection Pool
\n
java
// ConnectionPool as singleton to manage all connections\npublicclassConnectionPool {\n privatestaticfinalConnectionPoolinstance=newConnectionPool();\n \n publicstatic ConnectionPool getInstance() {\n return instance;\n }\n}\n
When using a DI container (Spring, Guice); provides testability and flexibility
\n
\n
\n
Static Class
\n
For stateless utilities; simpler than singleton but can’t implement interfaces
\n
\n
\n
Enum Singleton
\n
For thread-safety and serialization guarantees in Java
\n
\n
\n
Factory Pattern
\n
When you need flexibility to create different implementations
\n
\n
\n
Service Locator
\n
When you need dynamic service registration (though often considered an anti-pattern)
\n
\n\n
\n\n
📝 Best Practices
\n\n
Prefer Dependency Injection: Use DI container (Spring, Guice) instead of manual singleton management
\n
Make Thread-Safe: Use Bill Pugh Singleton or eager initialization for multi-threaded applications
\n
Document Constraints: Clearly state that your class is a singleton and why
\n
Provide Test Hooks: Add methods to reset state for testing
\n
Avoid Mutable State: Keep singleton data immutable or use thread-safe collections
\n
Consider Enum Singleton: In Java, enum provides the most robust singleton implementation
\n
Avoid as Service Locator: Don’t use singleton to hide dependencies; use dependency injection
\n\n\n
🎓 Related Patterns
\n
\n
Factory Pattern: Often works with Singleton to control creation
\n
Lazy Initialization: Deferring object creation until first use
\n
Builder Pattern: Can be used to construct complex singleton objects
\n
Object Pool Pattern: Similar in controlling limited resources
\n
\n\n
📚 References
\n
\n
Gang of Four Design Patterns
\n
Effective Java (Joshua Bloch)
\n
Spring Framework Singleton Scope
\n
Enum as Singleton in Java
\n
\n",
+ "contentMarkdown": "# Singleton Pattern\n\n## 📋 Overview\n\nThe **Singleton Pattern** ensures that a class has only one instance and provides a global point of access to it. This is a creational pattern that restricts object instantiation to a single instance while providing a mechanism to access that instance universally.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- You need to guarantee that only one instance of a class exists throughout the application lifecycle\n- Multiple instances would cause logical errors or resource conflicts (e.g., database connections, configuration managers, logging services)\n- You need a globally accessible point of access to this single instance without passing references through all layers\n\n**Use When:**\n- You need a single, shared resource manager (connection pools, thread pools, caches)\n- You need a centralized configuration holder or registry\n- You need exactly one instance of a service to coordinate system-wide activities\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| **Singleton** | Ensures only one instance exists via private constructor; provides static method to access the single instance |\n| **Client** | Accesses the singleton instance through the public static accessor method |\n\n**Key Characteristics:**\n- Private constructor prevents external instantiation\n- Static instance variable holds the single object\n- Public static accessor method (`getInstance()`) returns the instance\n- Thread-safety considerations for multi-threaded environments\n\n---\n\n## 💡 Implementation Strategies\n\nThis pattern has multiple implementations, each with different trade-offs:\n\n### 1. **Eager Initialization**\n```java\npublic class EagerInitializedSingleton {\n private static final EagerInitializedSingleton instance = \n new EagerInitializedSingleton();\n \n private EagerInitializedSingleton() { }\n \n public static EagerInitializedSingleton getInstance() {\n return instance;\n }\n}\n```\n**Reasoning:** Instance created when class is loaded. Thread-safe by default but allocates memory immediately.\n\n### 2. **Lazy Initialization with Synchronization**\n```java\npublic class ThreadSafeSingleton {\n private static ThreadSafeSingleton instance;\n \n private ThreadSafeSingleton() { }\n \n public static synchronized ThreadSafeSingleton getInstance() {\n if (instance == null) {\n instance = new ThreadSafeSingleton();\n }\n return instance;\n }\n}\n```\n**Reasoning:** Creates instance on first use. Synchronized method ensures thread-safety but causes synchronization overhead on every call.\n\n### 3. **Double-Checked Locking**\n```java\npublic class ThreadSafeSingleton {\n private static ThreadSafeSingleton instance;\n \n private ThreadSafeSingleton() { }\n \n public static ThreadSafeSingleton getInstance() {\n if (instance == null) {\n synchronized (ThreadSafeSingleton.class) {\n if (instance == null) {\n instance = new ThreadSafeSingleton();\n }\n }\n }\n return instance;\n }\n}\n```\n**Reasoning:** Checks instance twice—once outside lock, once inside. Reduces synchronization overhead while ensuring thread-safety.\n\n### 4. **Bill Pugh Singleton (Class Loader)**\n```java\npublic class BillPughSingleton {\n private BillPughSingleton() { }\n \n private static class SingletonHelper {\n private static final BillPughSingleton instance = \n new BillPughSingleton();\n }\n \n public static BillPughSingleton getInstance() {\n return SingletonHelper.instance;\n }\n}\n```\n**Reasoning:** Uses inner class to achieve lazy initialization. Thread-safe by design and efficient (no synchronization overhead).\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Singleton {\n -static instance: Singleton\n +getInstance(): Singleton\n }\n Client --> Singleton\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>Singleton: getInstance()\n Singleton-->>Client: instance\n```\n\n---\n\n## 🔀 Design Principles Emphasized\n\n| Principle | How Applied |\n|-----------|------------|\n| **Single Responsibility** | Singleton class has one job: manage the single instance |\n| **Dependency Inversion** | Clients depend on the abstraction (interface) rather than concrete class |\n| **Separation of Concerns** | Instance management is separated from business logic |\n| **Composition over Inheritance** | Rather than subclassing, dependency is injected or accessed via static method |\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- **Global Access:** Provides easy, centralized access to shared resource\n- **Controlled Instantiation:** Guarantees exactly one instance exists\n- **Lazy Initialization (Option Dependent):** Defers object creation until needed\n- **Memory Efficient:** Only one instance in memory\n- **Thread-Safe (Option Dependent):** Several implementations are inherently thread-safe\n\n### Disadvantages ❌\n- **Testing Difficulty:** Hard to mock for unit tests; global state complicates testing\n- **Hidden Dependencies:** Not obvious that code depends on a singleton; dependencies are implicit\n- **Synchronization Overhead:** Lock-based implementations add performance cost\n- **Violates Single Responsibility:** Often handles both instantiation and business logic\n- **Rigid:** Extending or replacing the singleton is difficult without modifying client code\n- **Global State:** Makes code less predictable and harder to reason about\n- **Concurrency Issues:** Some implementations (eager loading) may fail under specific multi-threaded scenarios\n\n---\n\n## 🚫 When NOT to Use\n\n| Scenario | Why Avoid |\n|----------|-----------|\n| **Stateful Objects** | Sharing state across all clients leads to unexpected side effects |\n| **Testable Systems** | Global dependencies make unit testing extremely difficult |\n| **Multiple Instances Needed** | If business logic later requires multiple instances, refactoring is painful |\n| **Distributed Systems** | Each JVM/process gets its own instance; doesn't guarantee global uniqueness |\n| **Simple Services** | Dependency Injection (DI) containers provide same benefits with better flexibility |\n\n---\n\n## ⚠️ Common Anti-Patterns & Misuses\n\n| Anti-Pattern | Problem | Solution |\n|--------------|---------|----------|\n| **Mutable Singleton** | Shared state gets corrupted by concurrent modifications | Make singleton immutable or use thread-safe collections |\n| **Singleton as Service Locator** | Hides dependencies and couples code to singleton | Use constructor injection instead |\n| **Testing Without Mock/Spy** | Tests affect each other via shared state | Provide reset method or use test-specific implementations |\n| **Singleton Inheritance** | Each subclass becomes a different singleton | Use composition; wrap the actual singleton |\n| **Unnecessary Singletons** | Over-use creates tight coupling | Prefer dependency injection via constructors |\n| **Non-Thread-Safe Singleton** | Race conditions in multi-threaded apps | Use double-checked locking or eager initialization |\n\n---\n\n## 🌍 Real-World Use Cases\n\n### Spring Framework\n```java\n// Spring beans are singletons by default\n@Service\npublic class UserService {\n // Only one instance in Spring Container\n}\n\n// Access via Dependency Injection\n@Component\npublic class UserController {\n @Autowired\n private UserService userService; // Singleton instance injected\n}\n```\n\n### Log4j / SLF4J\n```java\n// Logger is typically a singleton\nLogger logger = LoggerFactory.getLogger(MyClass.class);\n// Returns same logger instance for same class name\n```\n\n### Database Connection Pool\n```java\n// ConnectionPool as singleton to manage all connections\npublic class ConnectionPool {\n private static final ConnectionPool instance = new ConnectionPool();\n \n public static ConnectionPool getInstance() {\n return instance;\n }\n}\n```\n\n### Configuration Manager\n```java\n// Singleton holding application configuration\npublic class AppConfig {\n private static final AppConfig instance = new AppConfig();\n \n public String getDatabaseUrl() { /* ... */ }\n public int getMaxConnections() { /* ... */ }\n}\n```\n\n---\n\n## 🔗 Alternatives & Similar Patterns\n\n| Alternative | When to Prefer |\n|-------------|-----------------|\n| **Dependency Injection** | When using a DI container (Spring, Guice); provides testability and flexibility |\n| **Static Class** | For stateless utilities; simpler than singleton but can't implement interfaces |\n| **Enum Singleton** | For thread-safety and serialization guarantees in Java |\n| **Factory Pattern** | When you need flexibility to create different implementations |\n| **Service Locator** | When you need dynamic service registration (though often considered an anti-pattern) |\n\n---\n\n## 📝 Best Practices\n\n1. **Prefer Dependency Injection:** Use DI container (Spring, Guice) instead of manual singleton management\n2. **Make Thread-Safe:** Use Bill Pugh Singleton or eager initialization for multi-threaded applications\n3. **Document Constraints:** Clearly state that your class is a singleton and why\n4. **Provide Test Hooks:** Add methods to reset state for testing\n5. **Avoid Mutable State:** Keep singleton data immutable or use thread-safe collections\n6. **Consider Enum Singleton:** In Java, `enum` provides the most robust singleton implementation\n7. **Avoid as Service Locator:** Don't use singleton to hide dependencies; use dependency injection\n\n---\n\n## 🎓 Related Patterns\n\n- **Factory Pattern:** Often works with Singleton to control creation\n- **Lazy Initialization:** Deferring object creation until first use\n- **Builder Pattern:** Can be used to construct complex singleton objects\n- **Object Pool Pattern:** Similar in controlling limited resources\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Effective Java (Joshua Bloch)\n- Spring Framework Singleton Scope\n- Enum as Singleton in Java",
+ "relatedPatternIds": [
+ "builder",
+ "factory-method",
+ "abstract-factory",
+ "prototype"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation Strategies",
+ "1. **Eager Initialization**",
+ "2. **Lazy Initialization with Synchronization**",
+ "3. **Double-Checked Locking**",
+ "4. **Bill Pugh Singleton (Class Loader)**",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "🔀 Design Principles Emphasized",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "⚠️ Common Anti-Patterns & Misuses",
+ "🌍 Real-World Use Cases",
+ "Spring Framework",
+ "Log4j / SLF4J",
+ "Database Connection Pool",
+ "Configuration Manager",
+ "🔗 Alternatives & Similar Patterns",
+ "📝 Best Practices",
+ "🎓 Related Patterns",
+ "📚 References"
+ ],
+ "excerpt": "Singleton Pattern 📋 Overview The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. This is a creational pattern that restricts object instantiation to a single instance while providing a mechanism to acc",
+ "featured": false,
+ "previewImage": "/pattern-previews/singleton.svg",
+ "previewThumbnailImage": "/pattern-previews/singleton.svg"
+ },
+ {
+ "id": "state",
+ "slug": "state",
+ "name": "State",
+ "category": "gof",
+ "subcategory": "behavioral",
+ "summary": "The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.",
+ "intent": "The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.",
+ "applicability": [],
+ "advantages": [
+ "Eliminates large conditional statements",
+ "Locali"
+ ],
+ "disadvantages": [
+ "Increased number of classes",
+ "More complex than simple conditionals",
+ "State dependency coupling",
+ "Increased memory usage",
+ "Performance overhead"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "State",
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "pattern",
+ "allows",
+ "object",
+ "alter",
+ "its",
+ "behavior",
+ "when",
+ "internal",
+ "changes",
+ "will",
+ "appear",
+ "change",
+ "class",
+ "state transitions",
+ "state-driven behavior"
+ ],
+ "aliases": [
+ "state"
+ ],
+ "tags": [
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "gof-patterns/state",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/state",
+ "demoCodePaths": [
+ "gof-patterns/state/src/main/java",
+ "gof-patterns/state/src/main",
+ "gof-patterns/state/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
State Pattern
\n
📋 Overview
\n
The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
classDiagram\n class Context {\n -state: State\n +request()\n +setState(s: State)\n }\n class State {\n <<interface>>\n +handle(ctx: Context)\n }\n class ConcreteStateA\n class ConcreteStateB\n Context --> State\n State <|-- ConcreteStateA\n State <|-- ConcreteStateB\n
\n",
+ "contentMarkdown": "# Template Method Pattern\n\n## 📋 Overview\n\nThe **Template Method** pattern defines the skeleton of an algorithm in a base class, letting subclasses override specific steps.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Algorithm structure is fixed, but steps vary\n- Avoid code duplication in algorithm implementations\n- Control subclass overrides\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| AbstractClass | Defines template method and steps |\n| ConcreteClass | Implements specific steps |\n\n---\n\n## 💡 Code Example\n\n```java\npublic abstract class DataProcessor {\n public final void process() {\n readData();\n validateData();\n processData();\n writeData();\n }\n \n abstract void readData();\n abstract void validateData();\n abstract void processData();\n abstract void writeData();\n}\n\npublic class XMLProcessor extends DataProcessor {\n @Override\n void readData() { /* XML reading */ }\n \n @Override\n void validateData() { /* XML validation */ }\n \n @Override\n void processData() { /* XML processing */ }\n \n @Override\n void writeData() { /* XML writing */ }\n}\n\n// Usage\nDataProcessor processor = new XMLProcessor();\nprocessor.process();\n```\n\n**Reasoning:** Defines algorithm structure; lets subclasses implement steps; prevents duplication.\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class AbstractClass {\n +templateMethod()\n #primitiveOp1()\n #primitiveOp2()\n }\n class ConcreteClass\n AbstractClass <|-- ConcreteClass\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>AbstractClass: templateMethod()\n AbstractClass->>AbstractClass: primitiveOp1()\n AbstractClass->>AbstractClass: primitiveOp2()\n AbstractClass-->>Client: done\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Code reuse\n- Controls extension points\n- Defines skeleton once\n- Consistent algorithm structure\n- Promotes inheritance\n\n### Disadvantages ❌\n- Inheritance hierarchy required\n- Tight coupling between base and derived\n- Hollywood Principle violation possible\n- Inflexible for diverse algorithms\n- Violates Composition over Inheritance\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Framework hook methods\n- Stream processing pipelines\n- Database connection pooling\n- Junit test setup/teardown\n- Application lifecycle methods\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Template Method variations",
+ "relatedPatternIds": [
+ "observer",
+ "state",
+ "strategy",
+ "chain"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Template Method Pattern 📋 Overview The Template Method pattern defines the skeleton of an algorithm in a base class, letting subclasses override specific steps. 👥 Roles & Responsibilities Role Responsibility AbstractClass Defines template method and steps Co",
+ "featured": false,
+ "previewImage": "/pattern-previews/template-method.svg",
+ "previewThumbnailImage": "/pattern-previews/template-method.svg"
+ },
+ {
+ "id": "visitor",
+ "slug": "visitor",
+ "name": "Visitor",
+ "category": "gof",
+ "subcategory": "behavioral",
+ "summary": "The Visitor pattern represents an operation to be performed on elements of an object structure. It lets you define a new operation without changing the classes of the elements on which it operates.",
+ "intent": "The Visitor pattern represents an operation to be performed on elements of an object structure. It lets you define a new operation without changing the classes of the elements on which it operates.",
+ "applicability": [],
+ "advantages": [
+ "Separates operations from objects",
+ "Easy to add new operations",
+ "Gathers related operations",
+ "Follows Open/Closed Principle",
+ "Centrali"
+ ],
+ "disadvantages": [
+ "Difficult to add new element types",
+ "Violates Encapsulation",
+ "Double dispatch complexity",
+ "Hard to understand",
+ "Multiple pass traversals"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Visitor",
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "pattern",
+ "represents",
+ "operation",
+ "performed",
+ "elements",
+ "object",
+ "structure",
+ "lets",
+ "you",
+ "define",
+ "new",
+ "without",
+ "changing",
+ "classes",
+ "which",
+ "operates"
+ ],
+ "aliases": [
+ "visitor"
+ ],
+ "tags": [
+ "gof",
+ "behavioral",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "gof-patterns/visitor",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/gof-patterns/visitor",
+ "demoCodePaths": [
+ "gof-patterns/visitor/src/main/java",
+ "gof-patterns/visitor/src/main",
+ "gof-patterns/visitor/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Visitor Pattern
\n
📋 Overview
\n
The Visitor pattern represents an operation to be performed on elements of an object structure. It lets you define a new operation without changing the classes of the elements on which it operates.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Perform operations on complex object structures without changing their classes
\n
Add new operations to class hierarchy without modification
\n
Operations are related but scattered across classes
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Visitor
\n
Declares visit methods for each element type
\n
\n
\n
ConcreteVisitor
\n
Implements specific operations
\n
\n
\n
Element
\n
Accepts visitor
\n
\n
\n
ConcreteElement
\n
Implements accept method
\n
\n
\n
ObjectStructure
\n
Provides access to elements
\n
\n\n
\n\n
💡 Implementation
\n
Visitor pattern is particularly useful when you have:
Classes that shouldn’t be modified with new methods
\n
Need to gather data from object structure
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Visitor {\n <<interface>>\n +visitConcreteElementA(e)\n +visitConcreteElementB(e)\n }\n class ConcreteVisitor\n class Element {\n <<interface>>\n +accept(v: Visitor)\n }\n class ConcreteElementA\n class ConcreteElementB\n Visitor <|-- ConcreteVisitor\n Element <|-- ConcreteElementA\n Element <|-- ConcreteElementB\n Element --> Visitor\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n Client->>Element: accept(visitor)\n Element->>Visitor: visit(element)\n
\n
⚖️ Trade-offs
\n
Advantages ✅
\n
\n
Separates operations from objects
\n
Easy to add new operations
\n
Gathers related operations
\n
Follows Open/Closed Principle
\n
Centralizes operation logic
\n
\n
Disadvantages ❌
\n
\n
Difficult to add new element types
\n
Violates Encapsulation
\n
Double dispatch complexity
\n
Hard to understand
\n
Multiple pass traversals
\n
\n\n
🌍 Real-World Use Cases
\n
\n
Compiler AST visitors
\n
Document processors
\n
Report generators
\n
Tree structure operations
\n
Metrics collection tools
\n
\n\n
📚 References
\n
\n
Gang of Four Design Patterns
\n
Compiler design patterns
\n
\n",
+ "contentMarkdown": "# Visitor Pattern\n\n## 📋 Overview\n\nThe **Visitor** pattern represents an operation to be performed on elements of an object structure. It lets you define a new operation without changing the classes of the elements on which it operates.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Perform operations on complex object structures without changing their classes\n- Add new operations to class hierarchy without modification\n- Operations are related but scattered across classes\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| Visitor | Declares visit methods for each element type |\n| ConcreteVisitor | Implements specific operations |\n| Element | Accepts visitor |\n| ConcreteElement | Implements accept method |\n| ObjectStructure | Provides access to elements |\n\n---\n\n## 💡 Implementation\n\nVisitor pattern is particularly useful when you have:\n- Complex object hierarchies requiring multiple operations\n- Operations that change frequently\n- Classes that shouldn't be modified with new methods\n- Need to gather data from object structure\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Visitor {\n <>\n +visitConcreteElementA(e)\n +visitConcreteElementB(e)\n }\n class ConcreteVisitor\n class Element {\n <>\n +accept(v: Visitor)\n }\n class ConcreteElementA\n class ConcreteElementB\n Visitor <|-- ConcreteVisitor\n Element <|-- ConcreteElementA\n Element <|-- ConcreteElementB\n Element --> Visitor\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>Element: accept(visitor)\n Element->>Visitor: visit(element)\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Separates operations from objects\n- Easy to add new operations\n- Gathers related operations\n- Follows Open/Closed Principle\n- Centralizes operation logic\n\n### Disadvantages ❌\n- Difficult to add new element types\n- Violates Encapsulation\n- Double dispatch complexity\n- Hard to understand\n- Multiple pass traversals\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Compiler AST visitors\n- Document processors\n- Report generators\n- Tree structure operations\n- Metrics collection tools\n\n---\n\n## 📚 References\n\n- Gang of Four Design Patterns\n- Compiler design patterns",
+ "relatedPatternIds": [
+ "mediator",
+ "iterator",
+ "memento",
+ "interpreter"
+ ],
+ "categoryLabel": "GoF",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Visitor Pattern 📋 Overview The Visitor pattern represents an operation to be performed on elements of an object structure. It lets you define a new operation without changing the classes of the elements on which it operates. 👥 Roles & Responsibilities Role R",
+ "featured": false,
+ "previewImage": "/pattern-previews/visitor.svg",
+ "previewThumbnailImage": "/pattern-previews/visitor.svg"
+ },
+ {
+ "id": "model-view-presenter",
+ "slug": "model-view-presenter",
+ "name": "Model-View-Presenter",
+ "category": "architectural",
+ "summary": "The Model View Presenter (MVP) pattern separates presentation logic from business logic by introducing a presenter component that mediates between the view and model.",
+ "intent": "The Model View Presenter (MVP) pattern separates presentation logic from business logic by introducing a presenter component that mediates between the view and model.",
+ "applicability": [],
+ "advantages": [
+ "Clear separation of concerns",
+ "Testable UI logic",
+ "Reusable presenters",
+ "Framework independence",
+ "Flexible UI"
+ ],
+ "disadvantages": [
+ "More classes and complexity",
+ "Boilerplate code",
+ "Learning curve",
+ "Performance overhead",
+ "Over-engineering for simple UIs"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Model-View-Presenter",
+ "architectural",
+ "model view presenter",
+ "MVP",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "Model",
+ "View",
+ "Presenter",
+ "pattern",
+ "separates",
+ "presentation",
+ "logic",
+ "from",
+ "business",
+ "introducing",
+ "component",
+ "that",
+ "mediates",
+ "between",
+ "and"
+ ],
+ "aliases": [
+ "model view presenter",
+ "Model-View-Presenter",
+ "MVP"
+ ],
+ "tags": [
+ "architectural",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "architectural-patterns/model-view-presenter",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/architectural-patterns/model-view-presenter",
+ "demoCodePaths": [
+ "architectural-patterns/model-view-presenter/src/main/java",
+ "architectural-patterns/model-view-presenter/src/main",
+ "architectural-patterns/model-view-presenter/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Model-View-Presenter Pattern
\n
📋 Overview
\n
The Model-View-Presenter (MVP) pattern separates presentation logic from business logic by introducing a presenter component that mediates between the view and model.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Separate UI from business logic
\n
Make UI components testable
\n
Enable code reuse across UI frameworks
\n
Improve maintainability of UI code
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Model
\n
Business logic and data
\n
\n
\n
View
\n
Displays data, handles user interaction
\n
\n
\n
Presenter
\n
Coordinates Model and View
\n
\n\n
\n\n
💡 Implementation
\n
\n
View is passive (no business logic)
\n
Presenter handles all UI logic
\n
Model remains UI-independent
\n
MVP enables testing without UI framework
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Model\n class View {\n <<interface>>\n +render(data)\n }\n class Presenter {\n -model: Model\n -view: View\n +onViewEvent()\n }\n class ConcreteView\n View <|-- ConcreteView\n Presenter --> Model\n Presenter --> View\n ConcreteView --> Presenter\n
\n",
+ "contentMarkdown": "# Model-View-Presenter Pattern\n\n## 📋 Overview\n\nThe **Model-View-Presenter** (MVP) pattern separates presentation logic from business logic by introducing a presenter component that mediates between the view and model.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Separate UI from business logic\n- Make UI components testable\n- Enable code reuse across UI frameworks\n- Improve maintainability of UI code\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| Model | Business logic and data |\n| View | Displays data, handles user interaction |\n| Presenter | Coordinates Model and View |\n\n---\n\n## 💡 Implementation\n\n- View is passive (no business logic)\n- Presenter handles all UI logic\n- Model remains UI-independent\n- MVP enables testing without UI framework\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Model\n class View {\n <>\n +render(data)\n }\n class Presenter {\n -model: Model\n -view: View\n +onViewEvent()\n }\n class ConcreteView\n View <|-- ConcreteView\n Presenter --> Model\n Presenter --> View\n ConcreteView --> Presenter\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor User\n participant View\n participant Presenter\n participant Model\n User->>View: interact()\n View->>Presenter: event()\n Presenter->>Model: update()\n Model-->>Presenter: data\n Presenter->>View: render(data)\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Clear separation of concerns\n- Testable UI logic\n- Reusable presenters\n- Framework independence\n- Flexible UI\n\n### Disadvantages ❌\n- More classes and complexity\n- Boilerplate code\n- Learning curve\n- Performance overhead\n- Over-engineering for simple UIs\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Android applications\n- Desktop GUI applications\n- Web application presenters\n- Testing UI behavior\n- Multi-platform applications\n\n---\n\n## 📚 References\n\n- MVP architecture\n- Martin Fowler MVP article\n- Android MVP pattern",
+ "relatedPatternIds": [
+ "state-machine",
+ "service-locator",
+ "mediator",
+ "interpreter"
+ ],
+ "categoryLabel": "Architectural",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Model View Presenter Pattern 📋 Overview The Model View Presenter (MVP) pattern separates presentation logic from business logic by introducing a presenter component that mediates between the view and model. 👥 Roles & Responsibilities Role Responsibility Mode",
+ "featured": false,
+ "previewImage": "/pattern-previews/model-view-presenter.svg",
+ "previewThumbnailImage": "/pattern-previews/model-view-presenter.svg"
+ },
+ {
+ "id": "service-locator",
+ "slug": "service-locator",
+ "name": "Service Locator",
+ "category": "architectural",
+ "summary": "The Service Locator pattern centralizes logic for creating and accessing services, providing a single point for service instantiation and discovery.",
+ "intent": "The Service Locator pattern centralizes logic for creating and accessing services, providing a single point for service instantiation and discovery.",
+ "applicability": [],
+ "advantages": [
+ "Centrali"
+ ],
+ "disadvantages": [
+ "Hidden dependencies",
+ "Testing complexity",
+ "Global state issues",
+ "Service locator coupling",
+ "Anti-pattern warning"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Service Locator",
+ "architectural",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "note",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "⚠️ Note",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "Service",
+ "Locator",
+ "pattern",
+ "centralizes",
+ "logic",
+ "for",
+ "creating",
+ "and",
+ "accessing",
+ "services",
+ "providing",
+ "single",
+ "point",
+ "instantiation",
+ "discovery"
+ ],
+ "aliases": [
+ "service locator"
+ ],
+ "tags": [
+ "architectural",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "note",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "architectural-patterns/service-locator",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/architectural-patterns/service-locator",
+ "demoCodePaths": [
+ "architectural-patterns/service-locator/src/main/java",
+ "architectural-patterns/service-locator/src/main",
+ "architectural-patterns/service-locator/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Service Locator Pattern
\n
📋 Overview
\n
The Service Locator pattern centralizes logic for creating and accessing services, providing a single point for service instantiation and discovery.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Decouple service creation from usage
\n
Provide single service access point
\n
Enable service substitution
\n
Centralize service configuration
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
ServiceLocator
\n
Provides service access
\n
\n
\n
Service
\n
Defines service interface
\n
\n
\n
ServiceImpl
\n
Concrete service implementation
\n
\n\n
\n\n
⚠️ Note
\n
Service Locator is often considered an anti-pattern. Dependency Injection is the preferred modern approach.
\n\n
📊 Class Diagram
\n
classDiagram\n class Client\n class ServiceLocator {\n +getService(name)\n }\n class Service {\n <<interface>>\n +execute()\n }\n class ConcreteServiceA\n class ConcreteServiceB\n Client --> ServiceLocator\n Service <|-- ConcreteServiceA\n Service <|-- ConcreteServiceB\n ServiceLocator --> Service\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n Client->>ServiceLocator: getService(name)\n ServiceLocator-->>Client: Service\n Client->>Service: execute()\n
\n
⚖️ Trade-offs
\n
Advantages ✅
\n
\n
Centralized service management
\n
Easy service substitution
\n
Decouples client from creation
\n
Dynamic service loading
\n
\n
Disadvantages ❌
\n
\n
Hidden dependencies
\n
Testing complexity
\n
Global state issues
\n
Service locator coupling
\n
Anti-pattern warning
\n
\n\n
🌍 Real-World Use Cases
\n
\n
Legacy application service management
\n
Plugin systems
\n
Dynamic service discovery
\n
Configuration-driven services
\n
\n\n
📚 References
\n
\n
Martin Fowler Service Locator
\n
Dependency Injection advantages
\n
\n",
+ "contentMarkdown": "# Service Locator Pattern\n\n## 📋 Overview\n\nThe **Service Locator** pattern centralizes logic for creating and accessing services, providing a single point for service instantiation and discovery.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Decouple service creation from usage\n- Provide single service access point\n- Enable service substitution\n- Centralize service configuration\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| ServiceLocator | Provides service access |\n| Service | Defines service interface |\n| ServiceImpl | Concrete service implementation |\n\n---\n\n## ⚠️ Note\n\nService Locator is often considered an anti-pattern. **Dependency Injection** is the preferred modern approach.\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class ServiceLocator {\n +getService(name)\n }\n class Service {\n <>\n +execute()\n }\n class ConcreteServiceA\n class ConcreteServiceB\n Client --> ServiceLocator\n Service <|-- ConcreteServiceA\n Service <|-- ConcreteServiceB\n ServiceLocator --> Service\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>ServiceLocator: getService(name)\n ServiceLocator-->>Client: Service\n Client->>Service: execute()\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Centralized service management\n- Easy service substitution\n- Decouples client from creation\n- Dynamic service loading\n\n### Disadvantages ❌\n- Hidden dependencies\n- Testing complexity\n- Global state issues\n- Service locator coupling\n- Anti-pattern warning\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Legacy application service management\n- Plugin systems\n- Dynamic service discovery\n- Configuration-driven services\n\n---\n\n## 📚 References\n\n- Martin Fowler Service Locator\n- Dependency Injection advantages",
+ "relatedPatternIds": [
+ "model-view-presenter",
+ "state-machine",
+ "singleton",
+ "abstract-factory"
+ ],
+ "categoryLabel": "Architectural",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "⚠️ Note",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Service Locator Pattern 📋 Overview The Service Locator pattern centralizes logic for creating and accessing services, providing a single point for service instantiation and discovery. 👥 Roles & Responsibilities Role Responsibility ServiceLocator Provides ser",
+ "featured": true,
+ "previewImage": "/pattern-previews/service-locator.svg",
+ "previewThumbnailImage": "/pattern-previews/service-locator.svg"
+ },
+ {
+ "id": "state-machine",
+ "slug": "state-machine",
+ "name": "State Machine",
+ "category": "architectural",
+ "summary": "The State Machine pattern models complex workflows and state transitions using explicit state objects and transitions.",
+ "intent": "The State Machine pattern models complex workflows and state transitions using explicit state objects and transitions.",
+ "applicability": [],
+ "advantages": [
+ "Clear state modeling",
+ "Enforced valid transitions",
+ "Easy to visuali"
+ ],
+ "disadvantages": [
+ "Increased complexity",
+ "Many state classes",
+ "Overhead for simple cases",
+ "State explosion risk",
+ "Difficult to modify existing states"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "State Machine",
+ "architectural",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "State",
+ "Machine",
+ "pattern",
+ "models",
+ "complex",
+ "workflows",
+ "and",
+ "transitions",
+ "using",
+ "explicit",
+ "objects",
+ "state transitions",
+ "state-driven behavior"
+ ],
+ "aliases": [
+ "state machine"
+ ],
+ "tags": [
+ "architectural",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "architectural-patterns/state-machine",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/architectural-patterns/state-machine",
+ "demoCodePaths": [
+ "architectural-patterns/state-machine/src/main/java",
+ "architectural-patterns/state-machine/src/main",
+ "architectural-patterns/state-machine/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
State Machine Pattern
\n
📋 Overview
\n
The State Machine pattern models complex workflows and state transitions using explicit state objects and transitions.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Model complex workflows with multiple states
\n
Manage state transitions
\n
Enforce valid state transitions
\n
Handle state-dependent behavior
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
State
\n
Defines state interface
\n
\n
\n
ConcreteState
\n
Implements state-specific behavior
\n
\n
\n
StateMachine
\n
Context managing states
\n
\n\n
\n\n
💡 Implementation
\n
\n
States define valid transitions
\n
Transitions are explicit
\n
State machine validates transitions
\n
Prevents invalid state combinations
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class StateMachine {\n -current: State\n +handle(event)\n }\n class State {\n <<interface>>\n +onEvent(event)\n }\n class ConcreteStateA\n class ConcreteStateB\n class Event\n StateMachine --> State\n State <|-- ConcreteStateA\n State <|-- ConcreteStateB\n StateMachine --> Event\n
CQRS separates the write model (commands) from the read model (queries).\nWrites typically emit events; reads are served from a projection optimized for queries.
\n
An example: player profile writes (rename) emit events; profile reads come from a query store.
\n\n
🎯 Intent
\n
\n
Scale reads independently from writes
\n
Keep write-side rules strict while read-side stays fast and flexible
\n
Enable event-driven projections and eventually consistent read models
classDiagram\n class PlayerCommandService {\n +createPlayer(id, name)\n +changeDisplayName(id, name)\n }\n class EventStore {\n +append(event)\n +read(aggregateId) List~DomainEvent~\n }\n class Projector {\n +projectAggregate(aggregateId)\n }\n class PlayerReadModel {\n +apply(event)\n +get(id) PlayerView?\n }\n class DomainEvent {\n <<sealed>>\n +aggregateId()\n +occurredAt()\n }\n class PlayerCreated\n class PlayerDisplayNameChanged\n\n PlayerCommandService --> EventStore : append events\n Projector --> EventStore : read events\n Projector --> PlayerReadModel : apply events\n DomainEvent <|-- PlayerCreated\n DomainEvent <|-- PlayerDisplayNameChanged\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n participant Cmd as PlayerCommandService\n participant Store as EventStore\n participant Proj as Projector\n participant Read as PlayerReadModel\n\n Client->>Cmd: changeDisplayName(playerId, newName)\n Cmd->>Store: append(PlayerDisplayNameChanged)\n Store-->>Cmd: ok\n\n Client->>Proj: projectAggregate(playerId)\n Proj->>Store: read(playerId)\n Store-->>Proj: events\n loop events\n Proj->>Read: apply(event)\n end\n Client->>Read: get(playerId)\n Read-->>Client: PlayerView\n
\n
⚖️ Trade-offs
\n
Advantages ✅
\n
\n
Great for read-heavy systems (leaderboards, profiles)
\n
Clear separation of concerns
\n
Works naturally with event sourcing (optional)
\n
\n
Disadvantages ❌
\n
\n
Eventual consistency between write and read sides
\n
Projection code becomes part of your critical path
\n
\n",
+ "contentMarkdown": "# CQRS Pattern (Command Query Responsibility Segregation)\n\n## 📋 Overview\n\n**CQRS** separates the **write model** (commands) from the **read model** (queries).\nWrites typically emit **events**; reads are served from a projection optimized for queries.\n\nAn example: player profile writes (rename) emit events; profile reads come from a query store.\n\n---\n\n## 🎯 Intent\n\n- Scale reads independently from writes\n- Keep write-side rules strict while read-side stays fast and flexible\n- Enable event-driven projections and eventually consistent read models\n\n---\n\n## 💡 Code Example\n\n```java\ncommands.createPlayer(\"player-42\", \"RogueMage\");\ncommands.changeDisplayName(\"player-42\", \"RogueMage_2\");\n\nprojector.projectAggregate(\"player-42\");\nvar view = readModel.get(\"player-42\").orElseThrow();\n```\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class PlayerCommandService {\n +createPlayer(id, name)\n +changeDisplayName(id, name)\n }\n class EventStore {\n +append(event)\n +read(aggregateId) List~DomainEvent~\n }\n class Projector {\n +projectAggregate(aggregateId)\n }\n class PlayerReadModel {\n +apply(event)\n +get(id) PlayerView?\n }\n class DomainEvent {\n <>\n +aggregateId()\n +occurredAt()\n }\n class PlayerCreated\n class PlayerDisplayNameChanged\n\n PlayerCommandService --> EventStore : append events\n Projector --> EventStore : read events\n Projector --> PlayerReadModel : apply events\n DomainEvent <|-- PlayerCreated\n DomainEvent <|-- PlayerDisplayNameChanged\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n participant Cmd as PlayerCommandService\n participant Store as EventStore\n participant Proj as Projector\n participant Read as PlayerReadModel\n\n Client->>Cmd: changeDisplayName(playerId, newName)\n Cmd->>Store: append(PlayerDisplayNameChanged)\n Store-->>Cmd: ok\n\n Client->>Proj: projectAggregate(playerId)\n Proj->>Store: read(playerId)\n Store-->>Proj: events\n loop events\n Proj->>Read: apply(event)\n end\n Client->>Read: get(playerId)\n Read-->>Client: PlayerView\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n\n- Great for read-heavy systems (leaderboards, profiles)\n- Clear separation of concerns\n- Works naturally with event sourcing (optional)\n\n### Disadvantages ❌\n\n- Eventual consistency between write and read sides\n- Projection code becomes part of your critical path",
+ "relatedPatternIds": [
+ "transactional-outbox",
+ "saga",
+ "pipes-and-filters",
+ "rate-limiter"
+ ],
+ "categoryLabel": "Enterprise Integration",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌"
+ ],
+ "excerpt": "CQRS Pattern (Command Query Responsibility Segregation) 📋 Overview CQRS separates the write model (commands) from the read model (queries). Writes typically emit events ; reads are served from a projection optimized for queries. An example: player profile wri",
+ "featured": false,
+ "previewImage": "/pattern-previews/cqrs.svg",
+ "previewThumbnailImage": "/pattern-previews/cqrs.svg"
+ },
+ {
+ "id": "pipes-and-filters",
+ "slug": "pipes-and-filters",
+ "name": "Pipes and Filters",
+ "category": "enterprise-integration",
+ "summary": "The Pipes and Filters pattern processes data through a series of independent, modular processing components (filters) connected by data flow channels (pipes).",
+ "intent": "The Pipes and Filters pattern processes data through a series of independent, modular processing components (filters) connected by data flow channels (pipes).",
+ "applicability": [],
+ "advantages": [
+ "Modularity and reusability",
+ "Flexible data processing",
+ "Parallel processing support",
+ "Easy to reconfigure",
+ "Independent testing"
+ ],
+ "disadvantages": [
+ "Complexity with many filters",
+ "Data transformation overhead",
+ "Error handling complexity",
+ "Debugging difficulty",
+ "Performance considerations"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Pipes and Filters",
+ "enterprise-integration",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "Pipes",
+ "and",
+ "Filters",
+ "pattern",
+ "processes",
+ "data",
+ "through",
+ "series",
+ "independent",
+ "modular",
+ "processing",
+ "components",
+ "connected",
+ "flow",
+ "channels"
+ ],
+ "aliases": [
+ "pipes and filters"
+ ],
+ "tags": [
+ "enterprise-integration",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "enterprise-integration-patterns/pipes-and-filters",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/enterprise-integration-patterns/pipes-and-filters",
+ "demoCodePaths": [
+ "enterprise-integration-patterns/pipes-and-filters/src/main/java",
+ "enterprise-integration-patterns/pipes-and-filters/src/main",
+ "enterprise-integration-patterns/pipes-and-filters/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Pipes and Filters Pattern
\n
📋 Overview
\n
The Pipes and Filters pattern processes data through a series of independent, modular processing components (filters) connected by data flow channels (pipes).
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Process complex workflows through independent stages
\n
Enable modular, reusable components
\n
Support different processing orders
\n
Parallel and sequential processing
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Filter
\n
Independent processing component
\n
\n
\n
Pipe
\n
Data flow channel between filters
\n
\n
\n
Source
\n
Produces data
\n
\n
\n
Sink
\n
Consumes final result
\n
\n\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Source\n class Pipe\n class Filter {\n +process(data)\n }\n class Sink\n Source --> Pipe\n Pipe --> Filter\n Filter --> Pipe\n Pipe --> Sink\n
\n",
+ "contentMarkdown": "# Pipes and Filters Pattern\n\n## 📋 Overview\n\nThe **Pipes and Filters** pattern processes data through a series of independent, modular processing components (filters) connected by data flow channels (pipes).\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Process complex workflows through independent stages\n- Enable modular, reusable components\n- Support different processing orders\n- Parallel and sequential processing\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| Filter | Independent processing component |\n| Pipe | Data flow channel between filters |\n| Source | Produces data |\n| Sink | Consumes final result |\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Source\n class Pipe\n class Filter {\n +process(data)\n }\n class Sink\n Source --> Pipe\n Pipe --> Filter\n Filter --> Pipe\n Pipe --> Sink\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n participant Source\n participant Pipe1\n participant Filter\n participant Pipe2\n participant Sink\n Source->>Pipe1: emit(data)\n Pipe1->>Filter: data\n Filter->>Pipe2: processed\n Pipe2->>Sink: processed\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Modularity and reusability\n- Flexible data processing\n- Parallel processing support\n- Easy to reconfigure\n- Independent testing\n\n### Disadvantages ❌\n- Complexity with many filters\n- Data transformation overhead\n- Error handling complexity\n- Debugging difficulty\n- Performance considerations\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Unix pipelines\n- Data ETL processes\n- Image processing pipelines\n- Stream processing frameworks\n- Log processing\n\n---\n\n## 📚 References\n\n- Enterprise Integration Patterns\n- Data pipeline architecture",
+ "relatedPatternIds": [
+ "command",
+ "interpreter",
+ "mediator",
+ "memento"
+ ],
+ "categoryLabel": "Enterprise Integration",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Pipes and Filters Pattern 📋 Overview The Pipes and Filters pattern processes data through a series of independent, modular processing components (filters) connected by data flow channels (pipes). 👥 Roles & Responsibilities Role Responsibility Filter Independ",
+ "featured": false,
+ "previewImage": "/pattern-previews/pipes-and-filters.svg",
+ "previewThumbnailImage": "/pattern-previews/pipes-and-filters.svg"
+ },
+ {
+ "id": "saga",
+ "slug": "saga",
+ "name": "Saga",
+ "category": "enterprise-integration",
+ "summary": "The Saga pattern manages a long running business transaction across multiple services by splitting it into steps . Each step has an optional compensation that undoes the work if a later step fails.",
+ "intent": "The Saga pattern manages a long running business transaction across multiple services by splitting it into steps . Each step has an optional compensation that undoes the work if a later step fails. An example: buying a legendary item may touch inventory , wallet , and granting services.",
+ "applicability": [],
+ "advantages": [
+ "Works well with microservices and async messaging",
+ "Handles partial failures without global locks",
+ "Encourages explicit recovery design"
+ ],
+ "disadvantages": [],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Saga",
+ "enterprise-integration",
+ "overview",
+ "intent",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "📋 Overview",
+ "🎯 Intent",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "The",
+ "pattern",
+ "manages",
+ "long",
+ "running",
+ "business",
+ "transaction",
+ "across",
+ "multiple",
+ "services",
+ "splitting",
+ "into",
+ "steps",
+ "Each",
+ "step",
+ "has",
+ "optional",
+ "compensation",
+ "that",
+ "undoes",
+ "work",
+ "later",
+ "fails",
+ "example",
+ "buying",
+ "legendary",
+ "item",
+ "may",
+ "touch",
+ "inventory",
+ "wallet",
+ "and",
+ "granting",
+ "message flow",
+ "distributed transaction"
+ ],
+ "aliases": [
+ "saga"
+ ],
+ "tags": [
+ "enterprise-integration",
+ "overview",
+ "intent",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages"
+ ],
+ "githubPath": "enterprise-integration-patterns/saga",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/enterprise-integration-patterns/saga",
+ "demoCodePaths": [
+ "enterprise-integration-patterns/saga/src/main/java",
+ "enterprise-integration-patterns/saga/src/main",
+ "enterprise-integration-patterns/saga/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Saga Pattern
\n
📋 Overview
\n
The Saga pattern manages a long-running business transaction across multiple services by splitting it into steps.\nEach step has an optional compensation that undoes the work if a later step fails.
\n
An example: buying a legendary item may touch inventory, wallet, and granting services.
\n\n
🎯 Intent
\n
\n
Replace distributed transactions (2PC) with explicit orchestration + compensations
\n
Make partial failure handling intentional and testable
Compensations are not always perfect (undo may be best-effort)
\n
Requires careful modeling of state and retries/timeouts
\n
\n",
+ "contentMarkdown": "# Saga Pattern\n\n## 📋 Overview\n\nThe **Saga** pattern manages a long-running business transaction across multiple services by splitting it into **steps**.\nEach step has an optional **compensation** that undoes the work if a later step fails.\n\nAn example: buying a legendary item may touch **inventory**, **wallet**, and **granting** services.\n\n---\n\n## 🎯 Intent\n\n- Replace distributed transactions (2PC) with **explicit orchestration + compensations**\n- Make partial failure handling intentional and testable\n\n---\n\n## 💡 Code Example\n\n```java\nSaga saga = Saga.builder(\"purchase-legendary-sword\")\n .step(\"reserve-inventory\", reserve, release)\n .step(\"charge-wallet\", charge, refund)\n .step(\"grant-item\", grant, revoke)\n .build();\n\nSaga.Result result = saga.run();\n```\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Saga {\n +builder(name) Builder\n +run() Result\n }\n class Builder {\n +step(name, action, compensation) Builder\n +build() Saga\n }\n class Result {\n +success: boolean\n +log: List\n }\n Builder ..> Saga : builds\n Saga --> Result\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n participant Saga\n participant Inventory\n participant Wallet\n participant Granting\n\n Client->>Saga: run()\n Saga->>Inventory: reserve()\n Inventory-->>Saga: ok\n Saga->>Wallet: charge()\n Wallet-->>Saga: ok\n Saga->>Granting: grant()\n alt grant fails\n Granting-->>Saga: error\n Saga->>Wallet: refund() (compensate)\n Saga->>Inventory: release() (compensate)\n Saga-->>Client: failure\n else grant ok\n Granting-->>Saga: ok\n Saga-->>Client: success\n end\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Works well with microservices and async messaging\n- Handles partial failures without global locks\n- Encourages explicit recovery design\n\n### Disadvantages ❌\n- Compensations are not always perfect (undo may be best-effort)\n- Requires careful modeling of state and retries/timeouts",
+ "relatedPatternIds": [
+ "transactional-outbox",
+ "cqrs",
+ "pipes-and-filters",
+ "rate-limiter"
+ ],
+ "categoryLabel": "Enterprise Integration",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌"
+ ],
+ "excerpt": "Saga Pattern 📋 Overview The Saga pattern manages a long running business transaction across multiple services by splitting it into steps . Each step has an optional compensation that undoes the work if a later step fails. An example: buying a legendary item m",
+ "featured": true,
+ "previewImage": "/pattern-previews/saga.svg",
+ "previewThumbnailImage": "/pattern-previews/saga.svg"
+ },
+ {
+ "id": "transactional-outbox",
+ "slug": "transactional-outbox",
+ "name": "Transactional Outbox",
+ "category": "enterprise-integration",
+ "summary": "The Transactional Outbox pattern ensures that when your service writes domain data, it also writes the integration event to an outbox table in the same database transaction . A separate publisher later reads the outbox and publishes events to a broker.",
+ "intent": "The Transactional Outbox pattern ensures that when your service writes domain data, it also writes the integration event to an outbox table in the same database transaction . A separate publisher later reads the outbox and publishes events to a broker. An example: buying coins writes an order + emits coins.purchased without losing events during crashes.",
+ "applicability": [],
+ "advantages": [
+ "Strong consistency between domain write and event record",
+ "Simple recovery: publish from outbox after restart"
+ ],
+ "disadvantages": [],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Transactional Outbox",
+ "enterprise-integration",
+ "overview",
+ "intent",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "📋 Overview",
+ "🎯 Intent",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "The",
+ "Transactional",
+ "Outbox",
+ "pattern",
+ "ensures",
+ "that",
+ "when",
+ "your",
+ "service",
+ "writes",
+ "domain",
+ "data",
+ "also",
+ "integration",
+ "event",
+ "table",
+ "same",
+ "database",
+ "transaction",
+ "separate",
+ "publisher",
+ "later",
+ "reads",
+ "and",
+ "publishes",
+ "events",
+ "broker",
+ "example",
+ "buying",
+ "coins",
+ "order",
+ "emits",
+ "purchased",
+ "without",
+ "losing",
+ "during",
+ "crashes"
+ ],
+ "aliases": [
+ "transactional outbox"
+ ],
+ "tags": [
+ "enterprise-integration",
+ "overview",
+ "intent",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages"
+ ],
+ "githubPath": "enterprise-integration-patterns/transactional-outbox",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/enterprise-integration-patterns/transactional-outbox",
+ "demoCodePaths": [
+ "enterprise-integration-patterns/transactional-outbox/src/main/java",
+ "enterprise-integration-patterns/transactional-outbox/src/main",
+ "enterprise-integration-patterns/transactional-outbox/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Transactional Outbox Pattern
\n
📋 Overview
\n
The Transactional Outbox pattern ensures that when your service writes domain data, it also writes the integration event to an outbox table in the same database transaction.\nA separate publisher later reads the outbox and publishes events to a broker.
\n
An example: buying coins writes an order + emits coins.purchased without losing events during crashes.
\n\n
🎯 Intent
\n
\n
Prevent “write succeeded but event publish failed” inconsistencies
\n
Ensure at-least-once publication with a recoverable outbox
\n",
+ "contentMarkdown": "# Transactional Outbox Pattern\n\n## 📋 Overview\n\nThe **Transactional Outbox** pattern ensures that when your service writes domain data, it also writes the integration event to an **outbox table** in the **same database transaction**.\nA separate publisher later reads the outbox and publishes events to a broker.\n\nAn example: buying coins writes an order + emits `coins.purchased` without losing events during crashes.\n\n---\n\n## 🎯 Intent\n\n- Prevent “write succeeded but event publish failed” inconsistencies\n- Ensure at-least-once publication with a recoverable outbox\n\n---\n\n## 💡 Code Example\n\n```java\nvar tx = db.begin();\ntx.insertOrder(playerId, coins);\ntx.addOutbox(\"coins.purchased\", jsonPayload);\ntx.commit();\n\npublisher.publishOnce(100);\n```\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class PurchaseService\n class InMemoryDatabase\n class Transaction\n class OutboxPublisher\n class InMemoryMessageBroker\n PurchaseService --> InMemoryDatabase : begin tx\n Transaction --> InMemoryDatabase : commit\n OutboxPublisher --> InMemoryDatabase : drain outbox\n OutboxPublisher --> InMemoryMessageBroker : publish\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n participant Service as PurchaseService\n participant DB as Database\n participant Outbox as OutboxTable\n participant Pub as OutboxPublisher\n participant Broker as MessageBroker\n\n Client->>Service: purchaseCoins(playerId, coins)\n Service->>DB: BEGIN\n Service->>DB: INSERT Order\n Service->>Outbox: INSERT OutboxMessage\n Service->>DB: COMMIT\n\n Pub->>Outbox: poll batch\n Outbox-->>Pub: messages\n Pub->>Broker: publish(topic, payload)\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Strong consistency between domain write and event record\n- Simple recovery: publish from outbox after restart\n\n### Disadvantages ❌\n- Requires polling/streaming outbox and operational tooling\n- Needs idempotent publishing/consumers (at-least-once)",
+ "relatedPatternIds": [
+ "saga",
+ "cqrs",
+ "pipes-and-filters",
+ "observer"
+ ],
+ "categoryLabel": "Enterprise Integration",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌"
+ ],
+ "excerpt": "Transactional Outbox Pattern 📋 Overview The Transactional Outbox pattern ensures that when your service writes domain data, it also writes the integration event to an outbox table in the same database transaction . A separate publisher later reads the outbox ",
+ "featured": false,
+ "previewImage": "/pattern-previews/transactional-outbox.svg",
+ "previewThumbnailImage": "/pattern-previews/transactional-outbox.svg"
+ },
+ {
+ "id": "bulkhead",
+ "slug": "bulkhead",
+ "name": "Bulkhead",
+ "category": "reliability",
+ "summary": "The Bulkhead pattern limits concurrency to isolate failures and resource exhaustion. If one dependency becomes slow, it cannot consume all threads/connections.",
+ "intent": "The Bulkhead pattern limits concurrency to isolate failures and resource exhaustion. If one dependency becomes slow, it cannot consume all threads/connections. An example: isolate inventory calls so a slow inventory DB does not take down matchmaking.",
+ "applicability": [],
+ "advantages": [
+ "Prevents one dependency from exhausting capacity",
+ "Simple mental model (permits)"
+ ],
+ "disadvantages": [
+ "Needs si"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Bulkhead",
+ "reliability",
+ "overview",
+ "code example",
+ "class diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "📋 Overview",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "The",
+ "pattern",
+ "limits",
+ "concurrency",
+ "isolate",
+ "failures",
+ "and",
+ "resource",
+ "exhaustion",
+ "one",
+ "dependency",
+ "becomes",
+ "slow",
+ "cannot",
+ "consume",
+ "all",
+ "threads",
+ "connections",
+ "example",
+ "inventory",
+ "calls",
+ "does",
+ "not",
+ "take",
+ "down",
+ "matchmaking"
+ ],
+ "aliases": [
+ "bulkhead"
+ ],
+ "tags": [
+ "reliability",
+ "overview",
+ "code example",
+ "class diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages"
+ ],
+ "githubPath": "reliability-patterns/bulkhead",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/reliability-patterns/bulkhead",
+ "demoCodePaths": [
+ "reliability-patterns/bulkhead/src/main/java",
+ "reliability-patterns/bulkhead/src/main",
+ "reliability-patterns/bulkhead/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Bulkhead Pattern
\n
📋 Overview
\n
The Bulkhead pattern limits concurrency to isolate failures and resource exhaustion. If one dependency becomes slow, it cannot consume all threads/connections.
\n
An example: isolate inventory calls so a slow inventory DB does not take down matchmaking.
\n",
+ "contentMarkdown": "# Bulkhead Pattern\n\n## 📋 Overview\n\nThe **Bulkhead** pattern limits concurrency to isolate failures and resource exhaustion. If one dependency becomes slow, it cannot consume all threads/connections.\n\nAn example: isolate **inventory** calls so a slow inventory DB does not take down matchmaking.\n\n---\n\n## 💡 Code Example\n\n```java\nvar bulkhead = Bulkhead.builder(\"inventory-service\")\n .maxConcurrent(5)\n .maxWait(Duration.ofMillis(20))\n .build();\n\nbulkhead.execute(() -> loadInventory(playerId));\n```\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Bulkhead {\n +builder(name) Builder\n +execute(op) T\n }\n class Builder {\n +maxConcurrent(n) Builder\n +maxWait(d) Builder\n +build() Bulkhead\n }\n class BulkheadFullException\n Builder ..> Bulkhead : builds\n Bulkhead ..> BulkheadFullException : throws\n```\n\n\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n\n- Prevents one dependency from exhausting capacity\n- Simple mental model (permits)\n\n### Disadvantages ❌\n\n- Needs sizing and separate pools per dependency",
+ "relatedPatternIds": [
+ "rate-limiter",
+ "circuit-breaker",
+ "retry-backoff",
+ "hedge-requests"
+ ],
+ "categoryLabel": "Reliability",
+ "headingIndex": [
+ "📋 Overview",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌"
+ ],
+ "excerpt": "Bulkhead Pattern 📋 Overview The Bulkhead pattern limits concurrency to isolate failures and resource exhaustion. If one dependency becomes slow, it cannot consume all threads/connections. An example: isolate inventory calls so a slow inventory DB does not tak",
+ "featured": false,
+ "previewImage": "/pattern-previews/bulkhead.svg",
+ "previewThumbnailImage": "/pattern-previews/bulkhead.svg"
+ },
+ {
+ "id": "circuit-breaker",
+ "slug": "circuit-breaker",
+ "name": "Circuit Breaker",
+ "category": "reliability",
+ "summary": "The Circuit Breaker pattern prevents your system from repeatedly calling a failing dependency. When failures cross a threshold, the breaker opens and short circuits calls for a cool down period. After that, it allows limited trial calls (half open) to check whether the dependency recovered.",
+ "intent": "The Circuit Breaker pattern prevents your system from repeatedly calling a failing dependency. When failures cross a threshold, the breaker opens and short circuits calls for a cool down period. After that, it allows limited trial calls (half open) to check whether the dependency recovered.",
+ "applicability": [
+ "For in-process calls where failures are not correlated",
+ "When you cannot tolerate short-circuiting (must always attempt)",
+ "If you cannot operationally monitor and tune it"
+ ],
+ "advantages": [
+ "Prevents cascading failures and reduces blast radius",
+ "Gives dependencies time to recover (cool-down)",
+ "Improves latency by failing fast when unhealthy",
+ "Makes recovery behavior explicit and testable"
+ ],
+ "disadvantages": [
+ "Adds state and tuning parameters (thresholds, timers)",
+ "Wrong settings can cause flapping (open/close too frequently)",
+ "Needs good observability to diagnose and tune"
+ ],
+ "tradeOffs": [],
+ "alternatives": [
+ "For in-process calls where failures are not correlated",
+ "When you cannot tolerate short-circuiting (must always attempt)",
+ "If you cannot operationally monitor and tune it"
+ ],
+ "keywords": [
+ "Circuit Breaker",
+ "reliability",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example java 21 virtual threads",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "best practices",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Code Example (Java 21 + Virtual Threads)",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🚫 When NOT to Use",
+ "📝 Best Practices",
+ "The",
+ "Circuit",
+ "Breaker",
+ "pattern",
+ "prevents",
+ "your",
+ "system",
+ "from",
+ "repeatedly",
+ "calling",
+ "failing",
+ "dependency",
+ "When",
+ "failures",
+ "cross",
+ "threshold",
+ "opens",
+ "and",
+ "short",
+ "circuits",
+ "calls",
+ "for",
+ "cool",
+ "down",
+ "period",
+ "After",
+ "that",
+ "allows",
+ "limited",
+ "trial",
+ "half",
+ "open",
+ "check",
+ "whether",
+ "recovered",
+ "resilience",
+ "retry remote calls"
+ ],
+ "aliases": [
+ "circuit breaker"
+ ],
+ "tags": [
+ "reliability",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "code example java 21 virtual threads",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "when not to use",
+ "best practices"
+ ],
+ "githubPath": "reliability-patterns/circuit-breaker",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/reliability-patterns/circuit-breaker",
+ "demoCodePaths": [
+ "reliability-patterns/circuit-breaker/src/main/java",
+ "reliability-patterns/circuit-breaker/src/main",
+ "reliability-patterns/circuit-breaker/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 2,
+ "contentHtml": "\n
Circuit Breaker Pattern
\n
📋 Overview
\n
The Circuit Breaker pattern prevents your system from repeatedly calling a failing dependency.\nWhen failures cross a threshold, the breaker opens and short-circuits calls for a cool-down period.\nAfter that, it allows limited trial calls (half-open) to check whether the dependency recovered.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Stop cascading failures when a downstream service is unhealthy
\n
Reduce load on dependencies during incidents
\n
Fail fast (and consistently) instead of hanging or retrying endlessly
\n
\n
Use When:
\n
\n
You call remote services, databases, or third-party APIs
\n
Failures tend to be correlated (outages, overload, rate limits)
\n
You want controlled recovery behavior after an outage
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Client
\n
Calls execute(...) to run a protected operation
\n
\n
\n
CircuitBreaker
\n
Tracks health and blocks/permits calls based on state
\n",
+ "contentMarkdown": "# Idempotency Keys Pattern\n\n## 📋 Overview\n\n**Idempotency keys** ensure that repeated requests with the same key produce the same effect/result, even if the client retries due to timeouts.\n\nAn example: prevent double-charging when purchasing in-game currency if the client retries.\n\n---\n\n## 💡 Code Example\n\n```java\nvar store = IdempotencyKeys.builder(\"purchase\")\n .ttl(Duration.ofMinutes(5))\n .build();\n\nString result = store.execute(\"purchase:player-42:order-1001\", () -> chargeAndGrantCoins());\n```\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class IdempotencyKeys {\n +builder(name) Builder\n +execute(key, op) T\n }\n class Builder {\n +ttl(d) Builder\n +removeOnFailure(b) Builder\n +build() IdempotencyKeys\n }\n Builder ..> IdempotencyKeys : builds\n```\n\n",
+ "relatedPatternIds": [
+ "hedge-requests",
+ "retry-backoff",
+ "timeout-deadline-propagation",
+ "rate-limiter"
+ ],
+ "categoryLabel": "Reliability",
+ "headingIndex": [
+ "📋 Overview",
+ "💡 Code Example",
+ "📊 Class Diagram"
+ ],
+ "excerpt": "Idempotency Keys Pattern 📋 Overview Idempotency keys ensure that repeated requests with the same key produce the same effect/result, even if the client retries due to timeouts. An example: prevent double charging when purchasing in game currency if the client",
+ "featured": false,
+ "previewImage": "/pattern-previews/idempotency-keys.svg",
+ "previewThumbnailImage": "/pattern-previews/idempotency-keys.svg"
+ },
+ {
+ "id": "nullobject",
+ "slug": "nullobject",
+ "name": "Null Object",
+ "category": "reliability",
+ "summary": "The Null Object pattern provides an object as a surrogate for null references, avoiding null checks throughout the code.",
+ "intent": "The Null Object pattern provides an object as a surrogate for null references, avoiding null checks throughout the code.",
+ "applicability": [],
+ "advantages": [
+ "Eliminates null checks",
+ "Default behavior encapsulated",
+ "Cleaner code",
+ "Safer code",
+ "Visitor pattern support"
+ ],
+ "disadvantages": [
+ "Silent failures possible",
+ "Harder to detect issues",
+ "Performance overhead",
+ "Over-abstraction risk",
+ "Debugging complexity"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Null Object",
+ "reliability",
+ "nullobject",
+ "null-object",
+ "overview",
+ "intent",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "Null",
+ "Object",
+ "pattern",
+ "provides",
+ "surrogate",
+ "for",
+ "avoiding",
+ "checks",
+ "throughout",
+ "code"
+ ],
+ "aliases": [
+ "nullobject",
+ "Null Object",
+ "null-object"
+ ],
+ "tags": [
+ "reliability",
+ "overview",
+ "intent",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "reliability-patterns/nullobject",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/reliability-patterns/nullobject",
+ "demoCodePaths": [
+ "reliability-patterns/nullobject/src/main/java",
+ "reliability-patterns/nullobject/src/main",
+ "reliability-patterns/nullobject/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Null Object Pattern
\n
📋 Overview
\n
The Null Object pattern provides an object as a surrogate for null references, avoiding null checks throughout the code.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Eliminate null reference checks
\n
Provide default behavior for null case
\n
Improve code clarity
\n
Reduce NullPointerException risks
\n
\n\n
💡 Implementation
\n
Instead of:
\n
java
if (logger != null) {\n logger.log("message");\n}\n
Use:
\n
java
logger.log("message"); // Works with NullLogger\n
\n
📊 Class Diagram
\n
classDiagram\n class Client\n class AbstractObject {\n <<interface>>\n +operation()\n }\n class RealObject\n class NullObject\n Client --> AbstractObject\n AbstractObject <|-- RealObject\n AbstractObject <|-- NullObject\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n Client->>AbstractObject: operation()\n AbstractObject-->>Client: result\n
\n
⚖️ Trade-offs
\n
Advantages ✅
\n
\n
Eliminates null checks
\n
Default behavior encapsulated
\n
Cleaner code
\n
Safer code
\n
Visitor pattern support
\n
\n
Disadvantages ❌
\n
\n
Silent failures possible
\n
Harder to detect issues
\n
Performance overhead
\n
Over-abstraction risk
\n
Debugging complexity
\n
\n\n
🌍 Real-World Use Cases
\n
\n
Logging no-op implementations
\n
Optional services
\n
Collection empty implementations
\n
Null object patterns in frameworks
\n
\n\n
📚 References
\n
\n
Null Object pattern
\n
Optional design
\n
\n",
+ "contentMarkdown": "# Null Object Pattern\n\n## 📋 Overview\n\nThe **Null Object** pattern provides an object as a surrogate for null references, avoiding null checks throughout the code.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Eliminate null reference checks\n- Provide default behavior for null case\n- Improve code clarity\n- Reduce NullPointerException risks\n\n---\n\n## 💡 Implementation\n\nInstead of:\n```java\nif (logger != null) {\n logger.log(\"message\");\n}\n```\n\nUse:\n```java\nlogger.log(\"message\"); // Works with NullLogger\n```\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class AbstractObject {\n <>\n +operation()\n }\n class RealObject\n class NullObject\n Client --> AbstractObject\n AbstractObject <|-- RealObject\n AbstractObject <|-- NullObject\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>AbstractObject: operation()\n AbstractObject-->>Client: result\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Eliminates null checks\n- Default behavior encapsulated\n- Cleaner code\n- Safer code\n- Visitor pattern support\n\n### Disadvantages ❌\n- Silent failures possible\n- Harder to detect issues\n- Performance overhead\n- Over-abstraction risk\n- Debugging complexity\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Logging no-op implementations\n- Optional services\n- Collection empty implementations\n- Null object patterns in frameworks\n\n---\n\n## 📚 References\n\n- Null Object pattern\n- Optional design",
+ "relatedPatternIds": [
+ "interpreter",
+ "iterator",
+ "filter",
+ "servant"
+ ],
+ "categoryLabel": "Reliability",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Null Object Pattern 📋 Overview The Null Object pattern provides an object as a surrogate for null references, avoiding null checks throughout the code. 💡 Implementation Instead of: Use: 📊 Class Diagram 🔄 Sequence Diagram ⚖️ Trade offs Advantages ✅ Eliminat",
+ "featured": false,
+ "previewImage": "/pattern-previews/nullobject.svg",
+ "previewThumbnailImage": "/pattern-previews/nullobject.svg"
+ },
+ {
+ "id": "rate-limiter",
+ "slug": "rate-limiter",
+ "name": "Rate Limiter",
+ "category": "reliability",
+ "summary": "The Rate Limiter pattern controls how frequently an operation is allowed to run. It protects shared resources from spikes and prevents a single client from monopolizing capacity.",
+ "intent": "The Rate Limiter pattern controls how frequently an operation is allowed to run. It protects shared resources from spikes and prevents a single client from monopolizing capacity. An example: limit leaderboard refresh or matchmaking search calls per player to reduce load.",
+ "applicability": [],
+ "advantages": [
+ "Protects systems from bursts and abuse",
+ "Improves fairness across clients",
+ "Reduces tail latency under load"
+ ],
+ "disadvantages": [],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Rate Limiter",
+ "reliability",
+ "overview",
+ "intent",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "📋 Overview",
+ "🎯 Intent",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "The",
+ "Rate",
+ "Limiter",
+ "pattern",
+ "controls",
+ "how",
+ "frequently",
+ "operation",
+ "allowed",
+ "run",
+ "protects",
+ "shared",
+ "resources",
+ "from",
+ "spikes",
+ "and",
+ "prevents",
+ "single",
+ "client",
+ "monopolizing",
+ "capacity",
+ "example",
+ "limit",
+ "leaderboard",
+ "refresh",
+ "matchmaking",
+ "search",
+ "calls",
+ "per",
+ "player",
+ "reduce",
+ "load"
+ ],
+ "aliases": [
+ "rate limiter"
+ ],
+ "tags": [
+ "reliability",
+ "overview",
+ "intent",
+ "code example",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages"
+ ],
+ "githubPath": "reliability-patterns/rate-limiter",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/reliability-patterns/rate-limiter",
+ "demoCodePaths": [
+ "reliability-patterns/rate-limiter/src/main/java",
+ "reliability-patterns/rate-limiter/src/main",
+ "reliability-patterns/rate-limiter/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Rate Limiter Pattern
\n
📋 Overview
\n
The Rate Limiter pattern controls how frequently an operation is allowed to run. It protects shared resources from spikes and prevents a single client from monopolizing capacity.
\n
An example: limit leaderboard refresh or matchmaking search calls per player to reduce load.
Can increase latency if used for non-transient errors
\n
Needs strict limits (max attempts, max delay)
\n
\n",
+ "contentMarkdown": "# Retry with Backoff Pattern\n\n## 📋 Overview\n\n**Retry with backoff** retries transient failures while avoiding immediate, synchronized retries that amplify outages.\n\nAn example: retry transient **session validation** failures with exponential backoff and jitter.\n\n---\n\n## 💡 Code Example\n\n```java\nvar retry = RetryExecutor.builder(\"session-validate\")\n .maxAttempts(5)\n .baseDelay(Duration.ofMillis(50))\n .maxDelay(Duration.ofSeconds(1))\n .jitterRatio(0.2)\n .build();\n\nretry.execute(() -> callAuthService());\n```\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class RetryExecutor {\n +builder(name) Builder\n +execute(op) T\n }\n class Builder {\n +maxAttempts(n) Builder\n +baseDelay(d) Builder\n +maxDelay(d) Builder\n +jitterRatio(r) Builder\n +retryOn(p) Builder\n +build() RetryExecutor\n }\n Builder ..> RetryExecutor : builds\n```\n\n\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Recovers from transient failures\n- Reduces retry storms via backoff/jitter\n\n### Disadvantages ❌\n- Can increase latency if used for non-transient errors\n- Needs strict limits (max attempts, max delay)",
+ "relatedPatternIds": [
+ "bulkhead",
+ "circuit-breaker",
+ "timeout-deadline-propagation",
+ "hedge-requests"
+ ],
+ "categoryLabel": "Reliability",
+ "headingIndex": [
+ "📋 Overview",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌"
+ ],
+ "excerpt": "Retry with Backoff Pattern 📋 Overview Retry with backoff retries transient failures while avoiding immediate, synchronized retries that amplify outages. An example: retry transient session validation failures with exponential backoff and jitter. 📊 Class Diag",
+ "featured": true,
+ "previewImage": "/pattern-previews/retry-backoff.svg",
+ "previewThumbnailImage": "/pattern-previews/retry-backoff.svg"
+ },
+ {
+ "id": "timeout-deadline-propagation",
+ "slug": "timeout-deadline-propagation",
+ "name": "Timeout & Deadline Propagation",
+ "category": "reliability",
+ "summary": "Deadline propagation uses a single end to end time budget that is passed to all downstream calls. Each call uses the remaining budget so the system fails fast and predictably.",
+ "intent": "Deadline propagation uses a single end to end time budget that is passed to all downstream calls. Each call uses the remaining budget so the system fails fast and predictably. An example: a “join matchmaking” request has a 200ms budget across multiple services.",
+ "applicability": [],
+ "advantages": [],
+ "disadvantages": [],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Timeout & Deadline Propagation",
+ "reliability",
+ "timeout deadline propagation",
+ "Timeout and Deadline Propagation",
+ "overview",
+ "code example",
+ "class diagram",
+ "📋 Overview",
+ "💡 Code Example",
+ "📊 Class Diagram",
+ "Deadline",
+ "propagation",
+ "uses",
+ "single",
+ "end",
+ "time",
+ "budget",
+ "that",
+ "passed",
+ "all",
+ "downstream",
+ "calls",
+ "Each",
+ "call",
+ "the",
+ "remaining",
+ "system",
+ "fails",
+ "fast",
+ "and",
+ "predictably",
+ "example",
+ "join",
+ "matchmaking",
+ "request",
+ "has",
+ "200ms",
+ "across",
+ "multiple",
+ "services"
+ ],
+ "aliases": [
+ "timeout deadline propagation",
+ "Timeout & Deadline Propagation",
+ "Timeout and Deadline Propagation"
+ ],
+ "tags": [
+ "reliability",
+ "overview",
+ "code example",
+ "class diagram"
+ ],
+ "githubPath": "reliability-patterns/timeout-deadline-propagation",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/reliability-patterns/timeout-deadline-propagation",
+ "demoCodePaths": [
+ "reliability-patterns/timeout-deadline-propagation/src/main/java",
+ "reliability-patterns/timeout-deadline-propagation/src/main",
+ "reliability-patterns/timeout-deadline-propagation/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Timeout & Deadline Propagation Pattern
\n
📋 Overview
\n
Deadline propagation uses a single end-to-end time budget that is passed to all downstream calls. Each call uses the remaining budget so the system fails fast and predictably.
\n
An example: a “join matchmaking” request has a 200ms budget across multiple services.
classDiagram\n class Deadline {\n +after(timeout) Deadline\n +remaining() Duration\n +throwIfExpired(context)\n }\n class DeadlineExceededException\n Deadline ..> DeadlineExceededException : throws\n
\n",
+ "contentMarkdown": "# Timeout & Deadline Propagation Pattern\n\n## 📋 Overview\n\n**Deadline propagation** uses a single end-to-end time budget that is passed to all downstream calls. Each call uses the *remaining* budget so the system fails fast and predictably.\n\nAn example: a “join matchmaking” request has a 200ms budget across multiple services.\n\n---\n\n## 💡 Code Example\n\n```java\nDeadline deadline = Deadline.after(Duration.ofMillis(200));\n\ndeadline.throwIfExpired(\"pre-check\");\ncallProfile(deadline.remaining());\n\ndeadline.throwIfExpired(\"matchmaking\");\ncallMatchmaking(deadline.remaining());\n```\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Deadline {\n +after(timeout) Deadline\n +remaining() Duration\n +throwIfExpired(context)\n }\n class DeadlineExceededException\n Deadline ..> DeadlineExceededException : throws\n```\n\n",
+ "relatedPatternIds": [
+ "bulkhead",
+ "rate-limiter",
+ "hedge-requests",
+ "idempotency-keys"
+ ],
+ "categoryLabel": "Reliability",
+ "headingIndex": [
+ "📋 Overview",
+ "💡 Code Example",
+ "📊 Class Diagram"
+ ],
+ "excerpt": "Timeout & Deadline Propagation Pattern 📋 Overview Deadline propagation uses a single end to end time budget that is passed to all downstream calls. Each call uses the remaining budget so the system fails fast and predictably. An example: a “join matchmaking” ",
+ "featured": false,
+ "previewImage": "/pattern-previews/timeout-deadline-propagation.svg",
+ "previewThumbnailImage": "/pattern-previews/timeout-deadline-propagation.svg"
+ },
+ {
+ "id": "filter",
+ "slug": "filter",
+ "name": "Filter",
+ "category": "miscellaneous",
+ "summary": "The Filter pattern (or Criteria pattern) provides a way to filter collections of objects using different criteria in a flexible and reusable manner.",
+ "intent": "The Filter pattern (or Criteria pattern) provides a way to filter collections of objects using different criteria in a flexible and reusable manner.",
+ "applicability": [],
+ "advantages": [
+ "Flexible filtering logic",
+ "Reusable criteria",
+ "Easy combination of filters",
+ "Clear separation of concerns",
+ "Testable filter logic"
+ ],
+ "disadvantages": [
+ "Additional classes required",
+ "Performance with many filters",
+ "Memory overhead for criteria objects",
+ "Learning curve",
+ "Over-engineering for simple cases"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Filter",
+ "miscellaneous",
+ "criteria",
+ "criteria pattern",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "pattern",
+ "provides",
+ "way",
+ "collections",
+ "objects",
+ "using",
+ "different",
+ "flexible",
+ "and",
+ "reusable",
+ "manner"
+ ],
+ "aliases": [
+ "filter",
+ "criteria",
+ "criteria pattern"
+ ],
+ "tags": [
+ "miscellaneous",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "miscellaneous-patterns/filter",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/miscellaneous-patterns/filter",
+ "demoCodePaths": [
+ "miscellaneous-patterns/filter/src/main/java",
+ "miscellaneous-patterns/filter/src/main",
+ "miscellaneous-patterns/filter/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Filter Pattern
\n
📋 Overview
\n
The Filter pattern (or Criteria pattern) provides a way to filter collections of objects using different criteria in a flexible and reusable manner.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Filter collections by different criteria
\n
Combine multiple filter criteria
\n
Avoid multiple if-else statements
\n
Enable reusable filter components
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
Criteria
\n
Defines filtering interface
\n
\n
\n
ConcreteCriteria
\n
Implements specific filter logic
\n
\n
\n
Filter
\n
Applies criteria to collection
\n
\n\n
\n\n
💡 Implementation
\n
\n
Each filter criterion is a separate component
\n
Filters can be combined/chained
\n
Enables dynamic filtering logic
\n
Reusable and testable filters
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Client\n class Criteria {\n <<interface>>\n +meetCriteria(items)\n }\n class ConcreteCriteriaA\n class ConcreteCriteriaB\n class AndCriteria\n class OrCriteria\n Client --> Criteria\n Criteria <|-- ConcreteCriteriaA\n Criteria <|-- ConcreteCriteriaB\n Criteria <|-- AndCriteria\n Criteria <|-- OrCriteria\n AndCriteria --> Criteria\n OrCriteria --> Criteria\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n Client->>Criteria: meetCriteria(items)\n Criteria-->>Client: filteredItems\n
\n
⚖️ Trade-offs
\n
Advantages ✅
\n
\n
Flexible filtering logic
\n
Reusable criteria
\n
Easy combination of filters
\n
Clear separation of concerns
\n
Testable filter logic
\n
\n
Disadvantages ❌
\n
\n
Additional classes required
\n
Performance with many filters
\n
Memory overhead for criteria objects
\n
Learning curve
\n
Over-engineering for simple cases
\n
\n\n
🌍 Real-World Use Cases
\n
\n
Database query builders
\n
Collection filtering
\n
Stream filtering
\n
Search functionality
\n
Data validation chains
\n
\n\n
📚 References
\n
\n
Criteria Pattern
\n
Chain of Responsibility Pattern
\n
\n",
+ "contentMarkdown": "# Filter Pattern\n\n## 📋 Overview\n\nThe **Filter** pattern (or Criteria pattern) provides a way to filter collections of objects using different criteria in a flexible and reusable manner.\n\n---\n\n## 🎯 Intent\n\n**Problem Solved:**\n- Filter collections by different criteria\n- Combine multiple filter criteria\n- Avoid multiple if-else statements\n- Enable reusable filter components\n\n---\n\n## 👥 Roles & Responsibilities\n\n| Role | Responsibility |\n|------|-----------------|\n| Criteria | Defines filtering interface |\n| ConcreteCriteria | Implements specific filter logic |\n| Filter | Applies criteria to collection |\n\n---\n\n## 💡 Implementation\n\n- Each filter criterion is a separate component\n- Filters can be combined/chained\n- Enables dynamic filtering logic\n- Reusable and testable filters\n\n---\n\n## 📊 Class Diagram\n\n```mermaid\nclassDiagram\n class Client\n class Criteria {\n <>\n +meetCriteria(items)\n }\n class ConcreteCriteriaA\n class ConcreteCriteriaB\n class AndCriteria\n class OrCriteria\n Client --> Criteria\n Criteria <|-- ConcreteCriteriaA\n Criteria <|-- ConcreteCriteriaB\n Criteria <|-- AndCriteria\n Criteria <|-- OrCriteria\n AndCriteria --> Criteria\n OrCriteria --> Criteria\n```\n\n---\n\n## 🔄 Sequence Diagram\n\n```mermaid\nsequenceDiagram\n actor Client\n Client->>Criteria: meetCriteria(items)\n Criteria-->>Client: filteredItems\n```\n\n---\n\n## ⚖️ Trade-offs\n\n### Advantages ✅\n- Flexible filtering logic\n- Reusable criteria\n- Easy combination of filters\n- Clear separation of concerns\n- Testable filter logic\n\n### Disadvantages ❌\n- Additional classes required\n- Performance with many filters\n- Memory overhead for criteria objects\n- Learning curve\n- Over-engineering for simple cases\n\n---\n\n## 🌍 Real-World Use Cases\n\n- Database query builders\n- Collection filtering\n- Stream filtering\n- Search functionality\n- Data validation chains\n\n---\n\n## 📚 References\n\n- Criteria Pattern\n- Chain of Responsibility Pattern",
+ "relatedPatternIds": [
+ "lazy-sequence",
+ "servant",
+ "state-machine",
+ "iterator"
+ ],
+ "categoryLabel": "Miscellaneous",
+ "headingIndex": [
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References"
+ ],
+ "excerpt": "Filter Pattern 📋 Overview The Filter pattern (or Criteria pattern) provides a way to filter collections of objects using different criteria in a flexible and reusable manner. 👥 Roles & Responsibilities Role Responsibility Criteria Defines filtering interface",
+ "featured": false,
+ "previewImage": "/pattern-previews/filter.svg",
+ "previewThumbnailImage": "/pattern-previews/filter.svg"
+ },
+ {
+ "id": "lazy-sequence",
+ "slug": "lazy-sequence",
+ "name": "Lazy Sequence",
+ "category": "miscellaneous",
+ "summary": "The Lazy Sequence pattern defers sequence element computation until they're actually accessed, enabling efficient processing of potentially infinite sequences.",
+ "intent": "The Lazy Sequence pattern defers sequence element computation until they're actually accessed, enabling efficient processing of potentially infinite sequences.",
+ "applicability": [],
+ "advantages": [
+ "Deferred expensive computations",
+ "Memory efficient",
+ "Support infinite sequences",
+ "Streaming processing",
+ "Computation on demand"
+ ],
+ "disadvantages": [
+ "Harder to understand",
+ "Non-deterministic timing",
+ "Caching overhead",
+ "Debugging complexity",
+ "First-access latency"
+ ],
+ "tradeOffs": [],
+ "alternatives": [],
+ "keywords": [
+ "Lazy Sequence",
+ "miscellaneous",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references",
+ "📋 Overview",
+ "🎯 Intent",
+ "👥 Roles & Responsibilities",
+ "💡 Implementation",
+ "📊 Class Diagram",
+ "🔄 Sequence Diagram",
+ "⚖️ Trade-offs",
+ "Advantages ✅",
+ "Disadvantages ❌",
+ "🌍 Real-World Use Cases",
+ "📚 References",
+ "The",
+ "Lazy",
+ "Sequence",
+ "pattern",
+ "defers",
+ "element",
+ "computation",
+ "until",
+ "they",
+ "actually",
+ "accessed",
+ "enabling",
+ "efficient",
+ "processing",
+ "potentially",
+ "infinite",
+ "sequences"
+ ],
+ "aliases": [
+ "lazy sequence"
+ ],
+ "tags": [
+ "miscellaneous",
+ "overview",
+ "intent",
+ "roles responsibilities",
+ "implementation",
+ "class diagram",
+ "sequence diagram",
+ "trade-offs",
+ "advantages",
+ "disadvantages",
+ "real-world use cases",
+ "references"
+ ],
+ "githubPath": "miscellaneous-patterns/lazy-sequence",
+ "githubUrl": "https://github.com/SaumilP/design-patterns/tree/main/miscellaneous-patterns/lazy-sequence",
+ "demoCodePaths": [
+ "miscellaneous-patterns/lazy-sequence/src/main/java",
+ "miscellaneous-patterns/lazy-sequence/src/main",
+ "miscellaneous-patterns/lazy-sequence/src"
+ ],
+ "hasTests": true,
+ "readingTimeMinutes": 1,
+ "contentHtml": "
Lazy Sequence Pattern
\n
📋 Overview
\n
The Lazy Sequence pattern defers sequence element computation until they’re actually accessed, enabling efficient processing of potentially infinite sequences.
\n\n
🎯 Intent
\n
Problem Solved:
\n
\n
Defer expensive computations
\n
Handle potentially infinite sequences
\n
Support streaming data processing
\n
Reduce memory usage
\n
\n\n
👥 Roles & Responsibilities
\n
\n\n
\n
Role
\n
Responsibility
\n
\n\n\n
\n
LazySequence
\n
Defers element computation
\n
\n
\n
ElementGenerator
\n
Generates individual elements
\n
\n
\n
Client
\n
Accesses elements on demand
\n
\n\n
\n\n
💡 Implementation
\n
\n
Elements computed on first access
\n
Caching computed results
\n
Support for infinite sequences
\n
Memory-efficient processing
\n
\n\n
📊 Class Diagram
\n
classDiagram\n class Client\n class LazySequence {\n -cache: Map\n -generator: ElementGenerator\n +get(index)\n }\n class ElementGenerator {\n <<interface>>\n +compute(index)\n }\n Client --> LazySequence\n LazySequence --> ElementGenerator\n
\n
🔄 Sequence Diagram
\n
sequenceDiagram\n actor Client\n Client->>LazySequence: get(index)\n alt cached\n LazySequence-->>Client: element\n else not cached\n LazySequence->>ElementGenerator: compute(index)\n ElementGenerator-->>LazySequence: element\n LazySequence-->>Client: element\n end\n
+ This site treats the repository folders as the content source. Every card and detail page is generated from the pattern README files, with no backend and no duplicated site-specific content to maintain.
+