# Java Design Patterns — User Guide

## 1. Quick Start

Java Design Patterns is the largest open-source collection of design pattern implementations in Java. Each pattern lives in its own Maven module with a self-contained `App.java` entry point, unit tests, UML class diagrams, and a detailed README explaining intent, real-world analogies, and trade-offs. The repository serves as both a learning resource and a reference library for software engineers at every level.

**Key features:**

- 166 design pattern implementations spanning Creational, Structural, Behavioral, Concurrency, Architectural, and more
- Every pattern has a runnable `App.java` demonstrating the concept end-to-end
- UML class diagrams in the `etc/` directory for visual learners
- Comprehensive unit tests for every pattern using JUnit 5
- Multi-language README translations (Arabic, Bengali, Chinese, Danish, German, Spanish, French, Greek, Hindi, Indonesian, Italian, Japanese, Marathi, Nepali, Portuguese, Russian, Sinhala, Turkish, Urdu)
- Modern Java idioms — `var`, switch expressions, streams, lambdas, sealed classes

**Prerequisites:**

- Java 17 or later (JDK)
- Apache Maven 3.9+

**Quick build and run:**

```bash
git clone https://github.com/iluwatar/java-design-patterns.git
cd java-design-patterns
mvn compile -pl singleton -am
```

```bash
cd singleton
mvn exec:java -Dexec.mainClass="com.iluwatar.singleton.App"
```

```text
Cthulhu=com.iluwatar.singleton.IvoryTower@...
Cthulhu=com.iluwatar.singleton.IvoryTower@...
```

> [!TIP]
> You can run any pattern's demo the same way — replace `singleton` with the pattern module name (e.g., `observer`, `strategy`, `builder`).

**What to explore next:** Browse the full pattern catalog in section 3, pick a category that interests you, and run the demos.

## 2. Installation

### System Requirements

| Requirement | Minimum | Recommended |
|---|---|---|
| **Java (JDK)** | 17 | 21 (LTS) |
| **Maven** | 3.9+ | 3.9.6+ |
| **Git** | 2.x | Latest |
| **Disk space** | ~200 MB (source) | ~500 MB (with compiled classes) |
| **RAM** | 2 GB free | 4 GB free |

### Clone the Repository

```bash
git clone https://github.com/iluwatar/java-design-patterns.git
cd java-design-patterns
```

> [!IMPORTANT]
> The repository contains 3,500+ files. A shallow clone saves time if you only need the latest version: `git clone --depth 1 https://github.com/iluwatar/java-design-patterns.git`

### Build All Patterns

```bash
mvn clean install -DskipTests
```

```text
[INFO] Reactor Summary for Java Design Patterns 1.26.0-SNAPSHOT:
[INFO] java-design-patterns .......................... SUCCESS
[INFO] abstract-document ............................. SUCCESS
[INFO] abstract-factory .............................. SUCCESS
...
[INFO] BUILD SUCCESS
```

### Build a Single Pattern

```bash
mvn compile -pl observer -am
```

The `-pl` flag selects the module; `-am` (also-make) builds its dependencies (the parent POM).

### Verify Your Installation

```bash
mvn test -pl singleton
```

```text
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
```

> [!WARNING]
> Some pattern modules (e.g., `microservices-*`, `health-check`, `anti-corruption-layer`) use Spring Boot and download additional dependencies on first build. Ensure you have a stable internet connection.

### IDE Setup

=== "IntelliJ IDEA"
    1. **File → Open** → select the root `pom.xml`
    2. Choose "Open as Project"
    3. IntelliJ imports all 166 modules automatically
    4. Run any `App.java` with the green play button

=== "Eclipse"
    1. **File → Import → Maven → Existing Maven Projects**
    2. Select the root directory
    3. Eclipse discovers all submodules
    4. Right-click any `App.java` → **Run As → Java Application**

=== "VS Code"
    1. Install the **Extension Pack for Java**
    2. Open the root folder
    3. The Java extension detects the Maven structure
    4. Click **Run** above any `main` method

### Install Troubleshooting

**Error: `Unsupported class file major version 65`**

Your Maven or IDE is using an older JDK. Set `JAVA_HOME` to JDK 17+:

```bash
export JAVA_HOME=/path/to/jdk-17
mvn clean install -DskipTests
```

**Error: `Could not resolve dependencies`**

Maven cannot reach a repository. Check your network and proxy settings in `~/.m2/settings.xml`. The project uses JitPack (`https://jitpack.io`) as an additional repository.

**Error: `OutOfMemoryError` during build**

Increase Maven's heap:

```bash
export MAVEN_OPTS="-Xmx2g"
mvn clean install -DskipTests
```

**Error: `Plugin execution not covered by lifecycle configuration` (Eclipse)**

This is an Eclipse/m2e issue. Go to **Window → Preferences → Maven → Errors/Warnings** and set "Plugin execution not covered" to "Warning" or "Ignore".

## 3. Pattern Catalog

The 166 patterns are organized by category. Each pattern module follows the same structure:

```text
pattern-name/
├── README.md          ← Intent, explanation, code examples, class diagram
├── pom.xml            ← Module build config
├── etc/               ← UML diagrams (.png, .urm.png)
└── src/
    ├── main/java/     ← Implementation
    └── test/java/     ← Unit tests
```

### Creational Patterns

Patterns that deal with object creation mechanisms.

| Pattern | Module | Description |
|---|---|---|
| Abstract Document | `abstract-document` | Dynamic properties with type safety via trait interfaces |
| Abstract Factory | `abstract-factory` | Create families of related objects without specifying concrete classes |
| Builder | `builder` | Construct complex objects step by step |
| Factory | `factory` | Centralized object creation logic |
| Factory Kit | `factory-kit` | Define a factory with separated builder and creator interfaces |
| Factory Method | `factory-method` | Defer instantiation to subclasses |
| Monostate | `monostate` | Shared state across all instances (alternative to Singleton) |
| Multiton | `multiton` | Named instances managed as a registry |
| Object Mother | `object-mother` | Pre-configured test object factory |
| Object Pool | `object-pool` | Reuse expensive-to-create objects |
| Property | `property` | Dynamic properties attached to objects |
| Prototype | `prototype` | Clone existing objects instead of creating new ones |
| Registry | `registry` | Well-known object lookup |
| Singleton | `singleton` | Ensure a class has only one instance |
| Step Builder | `step-builder` | Enforce a construction order via a fluent interface |
| Value Object | `value-object` | Immutable objects compared by value, not identity |

### Structural Patterns

Patterns that compose classes and objects into larger structures.

| Pattern | Module | Description |
|---|---|---|
| Adapter | `adapter` | Convert one interface to another |
| Bridge | `bridge` | Decouple abstraction from implementation |
| Composite | `composite` | Treat individual objects and compositions uniformly |
| Composite Entity | `composite-entity` | Coarse-grained object managing internal dependent objects |
| Composite View | `composite-view` | Build views from sub-view components |
| Converter | `converter` | Bidirectional mapping between types |
| Decorator | `decorator` | Attach additional behavior dynamically |
| Extension Objects | `extension-objects` | Add functionality without modifying existing classes |
| Facade | `facade` | Simplified interface to a complex subsystem |
| Flyweight | `flyweight` | Share fine-grained objects to reduce memory |
| Marker Interface | `marker-interface` | Empty interface to convey metadata |
| Private Class Data | `private-class-data` | Restrict access to class attributes |
| Proxy | `proxy` | Surrogate controlling access to another object |
| Twin | `twin` | Simulate multiple inheritance |
| Virtual Proxy | `virtual-proxy` | Defer expensive object creation until needed |

### Behavioral Patterns

Patterns that manage algorithms and communication between objects.

| Pattern | Module | Description |
|---|---|---|
| Acyclic Visitor | `acyclic-visitor` | Visitor without dependency cycles |
| Chain of Responsibility | `chain-of-responsibility` | Pass a request along a chain of handlers |
| Command | `command` | Encapsulate a request as an object |
| Interpreter | `interpreter` | Define a grammar and interpret sentences |
| Iterator | `iterator` | Sequential access to collection elements |
| Mediator | `mediator` | Centralized communication between objects |
| Memento | `memento` | Capture and restore object state |
| Null Object | `null-object` | Default behavior instead of null checks |
| Observer | `observer` | Notify dependents of state changes |
| Servant | `servant` | Shared behavior across classes without inheritance |
| Specification | `specification` | Combine business rules using boolean logic |
| State | `state` | Alter behavior when internal state changes |
| Strategy | `strategy` | Interchange algorithms at runtime |
| Template Method | `template-method` | Define algorithm skeleton, defer steps to subclasses |
| Visitor | `visitor` | Add operations to objects without modifying them |

### Concurrency Patterns

Patterns for managing multi-threaded and asynchronous execution.

| Pattern | Module | Description |
|---|---|---|
| Active Object | `active-object` | Decouple method invocation from execution in its own thread |
| Actor Model | `actor-model` | Message-driven concurrency with isolated actors |
| Async Method Invocation | `async-method-invocation` | Non-blocking method calls with callbacks |
| Backpressure | `backpressure` | Control data flow rate between producer and consumer |
| Balking | `balking` | Skip an action if the object is not in the right state |
| Double-Checked Locking | `double-checked-locking` | Reduce synchronization overhead for lazy init |
| Event-Based Asynchronous | `event-based-asynchronous` | Async operations with event-driven completion |
| Fanout-Fanin | `fanout-fanin` | Distribute work then aggregate results |
| Guarded Suspension | `guarded-suspension` | Block until a precondition is met |
| Half-Sync/Half-Async | `half-sync-half-async` | Separate sync and async processing layers |
| Leader Election | `leader-election` | Choose a coordinator among distributed nodes |
| Leader-Followers | `leader-followers` | Thread pool with a leader that accepts and dispatches |
| Lockable Object | `lockable-object` | Mutual exclusion on shared resources |
| Master-Worker | `master-worker` | Distribute work to parallel workers |
| Monitor | `monitor` | Mutual exclusion with condition variables |
| Producer-Consumer | `producer-consumer` | Decoupled production and consumption via a buffer |
| Promise | `promise` | Placeholder for an asynchronous result |
| Queue-Based Load Leveling | `queue-based-load-leveling` | Buffer requests to smooth out load spikes |
| Reactor | `reactor` | Demultiplex and dispatch I/O events |
| Thread Pool Executor | `thread-pool-executor` | Manage a pool of reusable threads |

### Architectural Patterns

Large-scale structural and organizational patterns.

| Pattern | Module | Description |
|---|---|---|
| BLoC | `bloc` | Business Logic Component — reactive state management |
| Clean Architecture | `clean-architecture` | Dependency rule: inner layers know nothing of outer |
| CQRS | `command-query-responsibility-segregation` | Separate read and write models |
| Data Bus | `data-bus` | Central communication channel for decoupled components |
| Event-Driven Architecture | `event-driven-architecture` | Async event dispatch and handling |
| Event Sourcing | `event-sourcing` | Persist state as a sequence of events |
| Flux | `flux` | Unidirectional data flow (Action → Dispatcher → Store → View) |
| Front Controller | `front-controller` | Single entry point for web requests |
| Hexagonal Architecture | `hexagonal-architecture` | Ports and adapters — isolate core from infrastructure |
| Intercepting Filter | `intercepting-filter` | Pre/post-processing pipeline for requests |
| Layered Architecture | `layered-architecture` | Horizontal layers with defined responsibilities |
| Model-View-Controller | `model-view-controller` | Separate model, view, and controller concerns |
| Model-View-Intent | `model-view-intent` | Unidirectional MVI cycle |
| Model-View-Presenter | `model-view-presenter` | Presenter mediates between model and view |
| Model-View-ViewModel | `model-view-viewmodel` | ViewModel exposes observable state to view |
| Monolithic Architecture | `monolithic-architecture` | Single deployable unit |
| Page Controller | `page-controller` | Per-page request handling |
| Presentation Model | `presentation-model` | UI-independent presentation logic |
| Saga | `saga` | Manage distributed transactions via compensating actions |
| Separated Interface | `separated-interface` | Interface in a different package from implementation |
| Service Layer | `service-layer` | Application boundary encapsulating business logic |
| Service-to-Worker | `service-to-worker` | Front controller delegates to command and view |
| Session Facade | `session-facade` | Coarse-grained interface to fine-grained subsystems |
| Strangler | `strangler` | Incrementally replace a legacy system |
| Template View | `templateview` | Render dynamic content with template markers |
| View Helper | `view-helper` | Encapsulate formatting logic outside the view |

### Microservices Patterns

| Pattern | Module | Description |
|---|---|---|
| Aggregator Microservices | `microservices-aggregrator` | Aggregate responses from multiple services |
| API Gateway | `microservices-api-gateway` | Single entry point routing to backend services |
| Client-Side UI Composition | `microservices-client-side-ui-composition` | Assemble UI from multiple micro-frontends |
| Distributed Tracing | `microservices-distributed-tracing` | Trace requests across services |
| Idempotent Consumer | `microservices-idempotent-consumer` | Safely process duplicate messages |
| Log Aggregation | `microservices-log-aggregation` | Centralize logs from multiple services |
| Self-Registration | `microservices-self-registration` | Services register themselves with a registry |

### Data Access Patterns

| Pattern | Module | Description |
|---|---|---|
| Data Access Object | `data-access-object` | Abstract data source access |
| DAO Factory | `dao-factory` | Factory for creating DAO instances |
| Data Mapper | `data-mapper` | Map between domain objects and data storage |
| Data Transfer Object | `data-transfer-object` | Carry data between processes |
| Identity Map | `identity-map` | Cache loaded objects to prevent duplicates |
| Metadata Mapping | `metadata-mapping` | Map objects to tables via metadata |
| Optimistic Offline Lock | `optimistic-offline-lock` | Version-based conflict detection |
| Repository | `repository` | Collection-like interface for domain object access |
| Serialized Entity | `serialized-entity` | Persist objects via serialization |
| Serialized LOB | `serialized-lob` | Store large objects as serialized blobs |
| Table Inheritance | `table-inheritance` | Map inheritance hierarchies to tables |
| Single Table Inheritance | `single-table-inheritance` | One table for an entire class hierarchy |
| Table Module | `table-module` | One class per database table with all logic |
| Transaction Script | `transaction-script` | Organize logic as procedural transactions |
| Unit of Work | `unit-of-work` | Track changes and commit them atomically |
| Version Number | `version-number` | Detect concurrent modifications via version field |

### Integration Patterns

| Pattern | Module | Description |
|---|---|---|
| Ambassador | `ambassador` | Helper service for remote resource access |
| Anti-Corruption Layer | `anti-corruption-layer` | Translate between bounded contexts |
| Circuit Breaker | `circuit-breaker` | Prevent cascading failures by failing fast |
| Gateway | `gateway` | Encapsulate access to external systems |
| Rate Limiting | `rate-limiting-pattern` | Control request throughput |
| Retry | `retry` | Retry failed operations with back-off |
| Throttling | `throttling` | Limit resource consumption rate |
| Tolerant Reader | `tolerant-reader` | Ignore unrecognized data in messages |

### Functional and Idiom Patterns

| Pattern | Module | Description |
|---|---|---|
| Callback | `callback` | Pass executable code as an argument |
| Collection Pipeline | `collection-pipeline` | Chain operations on collections |
| Combinator | `combinator` | Compose functions into complex operations |
| Currying | `currying` | Transform multi-arg function into chained single-arg |
| Double Dispatch | `double-dispatch` | Method resolution on both receiver and argument types |
| Execute Around | `execute-around` | Resource setup/cleanup wrapping a user action |
| Filterer | `filterer` | Composable filtering with type safety |
| Fluent Interface | `fluent-interface` | Method chaining for readable API calls |
| Function Composition | `function-composition` | Combine simple functions into complex ones |
| Monad | `monad` | Chain operations while managing side effects |
| Mute Idiom | `mute-idiom` | Suppress checked exceptions for fire-and-forget |
| Pipeline | `pipeline` | Ordered processing stages transforming data |
| Trampoline | `trampoline` | Stack-safe recursive computation |

### Other Patterns

| Pattern | Module | Description |
|---|---|---|
| Arrange-Act-Assert | `arrange-act-assert` | Test method structure pattern |
| Bytecode | `bytecode` | Virtual machine instruction encoding |
| Caching | `caching` | Store frequently accessed data for fast retrieval |
| Collecting Parameter | `collecting-parameter` | Pass a collection through methods to accumulate results |
| Commander | `commander` | Distributed command queue with retries |
| Component | `component` | Entity-component composition (game dev) |
| Context Object | `context-object` | Encapsulate request context across layers |
| CRTP | `curiously-recurring-template-pattern` | Static polymorphism via self-referencing generics |
| Data Locality | `data-locality` | Arrange data for CPU cache efficiency |
| Dependency Injection | `dependency-injection` | Invert object creation responsibility |
| Dirty Flag | `dirty-flag` | Avoid expensive recomputation when unchanged |
| Double Buffer | `double-buffer` | Render to a back buffer, then swap |
| Dynamic Proxy | `dynamic-proxy` | Runtime-generated proxy objects |
| Event Aggregator | `event-aggregator` | Central hub for event routing |
| Event Queue | `event-queue` | Decouple event senders and receivers via a queue |
| Feature Toggle | `feature-toggle` | Enable/disable features at runtime |
| Game Loop | `game-loop` | Fixed-timestep update loop for games |
| Health Check | `health-check` | Expose application health status |
| Lazy Loading | `lazy-loading` | Defer initialization until first use |
| Map Reduce | `map-reduce` | Parallel distributed data processing |
| Money | `money` | Value object for monetary amounts |
| Notification | `notification` | Collect validation errors instead of throwing |
| Page Object | `page-object` | UI test abstraction over page elements |
| Parameter Object | `parameter-object` | Group related parameters into a single object |
| Partial Response | `partial-response` | Return only requested fields |
| Poison Pill | `poison-pill` | Signal a consumer to shut down |
| Publish-Subscribe | `publish-subscribe` | Decoupled message broadcasting |
| RAII | `resource-acquisition-is-initialization` | Bind resource lifecycle to object scope |
| Role Object | `role-object` | Dynamically attach roles to objects |
| Service Locator | `service-locator` | Central registry for service lookup |
| Service Stub | `service-stub` | Test double replacing a real service |
| Sharding | `sharding` | Distribute data across multiple stores |
| Spatial Partition | `spatial-partition` | Organize objects by spatial location for fast queries |
| Special Case | `special-case` | Subclass that handles edge cases with standard behavior |
| Subclass Sandbox | `subclass-sandbox` | Provide operations to subclasses via protected methods |
| Type Object | `type-object` | Define categories as data instead of subclasses |
| Update Method | `update-method` | Per-frame update for game objects |

## 4. Core Usage

### Running a Pattern Demo

Every pattern includes an `App.java` with a `main` method:

```bash
# Build the pattern and its dependencies
mvn compile -pl <pattern-module> -am

# Run the demo
cd <pattern-module>
mvn exec:java -Dexec.mainClass="com.iluwatar.<package>.App"
```

For example, running the Observer pattern:

```bash
mvn compile -pl observer -am
cd observer
mvn exec:java -Dexec.mainClass="com.iluwatar.observer.App"
```

```text
Weather: rainy, 15°C, 0.0 bar
Orcs: The weather changed, brace for rain!
Hobbits: The weather changed, better stay inside!
```

> [!NOTE]
> The package name within `com.iluwatar` usually matches the module name with hyphens removed. For example, `chain-of-responsibility` becomes `com.iluwatar.chainofresponsibility`. Check the `App.java` in the pattern's `src/main/java/` directory for the exact fully-qualified class name.

### Reading a Pattern

Each pattern module README follows a consistent structure:

1. **Intent** — What problem does it solve?
2. **Real-world analogy** — A concrete scenario making the concept intuitive
3. **In plain words** — One-sentence explanation
4. **Wikipedia/authoritative definition** — Formal description
5. **Programmatic example** — Annotated Java code showing the pattern in action
6. **Class diagram** — UML visualization of the participants
7. **Applicability** — When to use (and when not to)
8. **Known uses** — Real-world JDK/library examples
9. **Consequences** — Trade-offs (benefits and drawbacks)
10. **Related patterns** — Links to complementary patterns
11. **Credits** — Books, articles, tutorials

> [!TIP]
> Start with the "Programmatic example" section — it shows the pattern's essence in working code. Then read "Applicability" to understand when the pattern fits your specific problem.

### Running Tests for a Pattern

```bash
mvn test -pl strategy
```

```text
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
```

Run tests for all patterns:

```bash
mvn test
```

### Using Patterns in Your Own Projects

These patterns are educational implementations. To apply them in your codebase:

1. **Study the pattern** — Read the module README and `App.java`
2. **Identify the participants** — Note the interfaces, abstract classes, and concrete classes
3. **Adapt to your domain** — Rename classes to match your problem space
4. **Simplify** — Production code may not need all participants shown in the demo

> [!WARNING]
> Do not add `java-design-patterns` as a Maven dependency. It is a learning repository, not a reusable library. Copy and adapt the patterns you need into your own codebase.

### Localized Content

Pattern READMEs are available in 18+ languages under `localization/<language-code>/`:

| Code | Language | Code | Language |
|---|---|---|---|
| `ar` | Arabic | `ja` | Japanese |
| `bn` | Bengali | `mr` | Marathi |
| `da` | Danish | `ne` | Nepali |
| `de` | German | `pt` | Portuguese |
| `el` | Greek | `ru` | Russian |
| `es` | Spanish | `si` | Sinhala |
| `fa` | Persian | `tr` | Turkish |
| `fr` | French | `ur` | Urdu |
| `hi` | Hindi | `zh` | Chinese |
| `id` | Indonesian | | |
| `it` | Italian | | |

Access translations at `localization/<code>/<pattern-name>/README.md`.

## 5. Common Tasks

### Finding the Right Pattern for a Problem

**Goal:** Identify which design pattern addresses your specific problem.

1. Identify the problem category:
   - "I need to create objects flexibly" → **Creational**
   - "I need to compose or adapt objects" → **Structural**
   - "I need to manage behavior or communication" → **Behavioral**
   - "I need to handle threads or async work" → **Concurrency**
   - "I need to organize large-scale structure" → **Architectural**
2. Scan the category table in section 3 for descriptions matching your need
3. Read the module README's "Applicability" section to confirm the fit
4. Run the demo to see the pattern in action

### Comparing Related Patterns

**Goal:** Understand the difference between similar patterns.

**Prerequisites:** Two or more pattern modules to compare.

1. Read both READMEs side by side (focus on "Intent" and "Applicability")
2. Run both demos and compare output
3. Look at the class diagrams in `etc/` for structural differences
4. Check the "Related Patterns" section in each README for explicit comparisons

Common comparisons:

| Pair | Key Difference |
|---|---|
| Strategy vs. State | Strategy swaps algorithms; State changes behavior based on internal state |
| Factory Method vs. Abstract Factory | Factory Method creates one product; Abstract Factory creates families |
| Decorator vs. Proxy | Decorator adds behavior; Proxy controls access |
| Observer vs. Pub-Sub | Observer is direct notification; Pub-Sub uses an intermediary channel |
| Adapter vs. Facade | Adapter converts one interface; Facade simplifies many |
| Command vs. Strategy | Command encapsulates a request; Strategy encapsulates an algorithm |

### Building a Subset of Patterns

**Goal:** Build only the patterns you care about to save time.

```bash
# Build three specific patterns
mvn compile -pl singleton,observer,strategy -am
```

```bash
# Run all tests for just those three
mvn test -pl singleton,observer,strategy
```

### Studying Concurrency Patterns Safely

**Goal:** Understand thread-safe patterns without race condition surprises.

1. Read the pattern README carefully — concurrency patterns often include timing-sensitive behavior
2. Run the demo and observe the interleaved output:

```bash
mvn compile -pl active-object -am
cd active-object
mvn exec:java -Dexec.mainClass="com.iluwatar.activeobject.App"
```

```text
Orc0 is eating!
Orc0 has finished eating!
Orc0 has started to roam the wastelands.
Orc1 is eating!
...
```

3. Examine the test in `src/test/java/` for assertions about concurrent behavior
4. Modify timing parameters in `App.java` to observe different interleavings

> [!NOTE]
> Output ordering for concurrency demos may vary between runs — this is expected behavior, not a bug.

### Using the Microservices Patterns

**Goal:** Run the multi-module microservices examples.

Several microservices patterns use Spring Boot and involve multiple services:

```bash
# Build the microservices API Gateway example
mvn compile -pl microservices-api-gateway -am
```

> [!IMPORTANT]
> Microservices patterns require Spring Boot (`spring-boot-starter-web`) and may start embedded web servers. Check each module's `pom.xml` for specific dependencies and port configuration.

The microservices modules typically include:
- A parent module with shared configuration
- Individual service modules (e.g., `image-microservice`, `price-microservice`)
- A gateway or aggregator module

### Contributing a New Pattern

**Goal:** Add a new design pattern to the collection.

1. Check existing patterns to avoid duplication
2. Check open issues — the community tracks requested patterns (e.g., Thread-Specific Storage [#3225](https://github.com/iluwatar/java-design-patterns/issues/3225))
3. Create a new module directory following the standard structure:

```text
my-pattern/
├── README.md
├── pom.xml
├── etc/
│   └── my-pattern.urm.png
└── src/
    ├── main/java/com/iluwatar/mypattern/
    │   └── App.java
    └── test/java/com/iluwatar/mypattern/
        └── AppTest.java
```

4. Add the module to the root `pom.xml` `<modules>` section
5. Follow the existing README format (Intent, Real-world analogy, Programmatic example, Class diagram, Applicability, Known uses, Consequences, Related patterns, Credits)
6. Write comprehensive JUnit 5 tests

See the Admin Guide for full contributing details and code conventions.

## 6. Troubleshooting

### Error: `Unsupported class file major version 65`

**Cause:** Your JDK version is too old. The project requires Java 17+.

**Solution:**
1. Check your Java version:
   ```bash
   java -version
   ```
2. Install JDK 17 or later
3. Set `JAVA_HOME` and ensure `mvn -version` shows the correct JDK

**Prevention:** Use a version manager like SDKMAN to install and switch between JDK versions.

### Error: `Could not resolve dependencies`

**Cause:** Maven cannot reach Maven Central or JitPack.

**Solution:**
1. Check internet connectivity
2. Check proxy settings in `~/.m2/settings.xml`
3. Clear the local cache and rebuild:
   ```bash
   rm -rf ~/.m2/repository/com/iluwatar
   mvn clean install -DskipTests
   ```

**Prevention:** Keep `~/.m2/settings.xml` configured for your environment and proxy.

### Error: `OutOfMemoryError` during full build

**Cause:** Building all 166 modules requires significant heap space.

**Solution:**
```bash
export MAVEN_OPTS="-Xmx2g -XX:MaxMetaspaceSize=512m"
mvn clean install -DskipTests
```

**Prevention:** Build only the modules you need with `-pl`.

### Tests fail intermittently in concurrency modules

**Cause:** Timing-dependent tests may behave differently under system load. Known issue: busy-waiting loops in some patterns ([#2977](https://github.com/iluwatar/java-design-patterns/issues/2977)).

**Solution:**
1. Re-run the failing test in isolation:
   ```bash
   mvn test -pl <module-name>
   ```
2. If the failure persists, check the issue tracker for known timing bugs
3. Increase test timeouts if running on CI with limited resources

**Prevention:** Run concurrency tests individually rather than in a full build under heavy system load.

> [!WARNING]
> Some patterns use `Thread.sleep()` for demonstration purposes. These sleeps can cause test flakiness in resource-constrained environments.

### Spring Boot patterns fail to start

**Cause:** Port conflicts or missing Spring dependencies.

**Solution:**
1. Check if another process is using the default port (usually 8080):
   ```bash
   lsof -i :8080
   ```
2. Ensure all dependencies are downloaded:
   ```bash
   mvn dependency:resolve -pl <module-name>
   ```

**Prevention:** Stop other local servers before running Spring-based pattern demos.

### IDE shows errors but Maven build succeeds

**Cause:** IDE index is out of sync with Maven's dependency resolution.

**Solution:**
1. **IntelliJ:** File → Invalidate Caches → Invalidate and Restart
2. **Eclipse:** Right-click project → Maven → Update Project
3. **VS Code:** Ctrl+Shift+P → "Java: Clean Java Language Server Workspace"

**Prevention:** Run `mvn install -DskipTests` from the command line after pulling changes, then refresh your IDE.

> [!TIP]
> If only a few modules show errors, build just those with `mvn compile -pl <module> -am` and re-import.

### Lombok annotations not recognized by IDE

**Cause:** Lombok requires annotation processing support in the IDE.

**Solution:**
1. **IntelliJ:** Settings → Build → Compiler → Annotation Processors → Enable
2. **Eclipse:** Install the Lombok plugin from `lombok.jar` (run `java -jar lombok.jar`)
3. **VS Code:** The Java extension handles Lombok automatically with the correct dependency

**Prevention:** Install the Lombok IDE plugin before importing the project.

## 7. FAQ

**Q: What Java version do I need?**

JDK 17 or later. The project uses modern Java features including `var` local variable type inference, switch expressions, and streams.

**Q: Can I use these patterns as a library dependency?**

No. This is an educational repository. Copy and adapt the specific pattern code you need into your own project. The patterns are intentionally self-contained for learning purposes.

**Q: How are these patterns different from the Gang of Four (GoF) book?**

The repository includes all 23 original GoF patterns plus over 140 additional patterns from other authoritative sources — Martin Fowler's enterprise patterns, game programming patterns, concurrency patterns, microservices patterns, and modern Java idioms. The implementations use modern Java rather than the C++/Smalltalk of the original book.

**Q: Why are some READMEs in other languages?**

The project has an active community of translators. English READMEs live at `<pattern>/README.md`; translations are in `localization/<language-code>/<pattern>/README.md`. Not every pattern has been translated to every language.

**Q: Is `model-view-viewmodel` licensed differently?**

Yes. The MVVM module uses the ZK framework, which is licensed under LGPL (see `lgpl-3.0.txt` in the repository root). All other modules are MIT-licensed.

**Q: Why do some modules use Spring Boot?**

Patterns like microservices, health check, anti-corruption layer, and CQRS benefit from a real web framework to demonstrate their concepts. These modules use Spring Boot 3.4.4.

**Q: How do I know which pattern to study first?**

Start with the classic GoF patterns: Singleton, Factory Method, Observer, Strategy, Decorator, and Adapter. These are the most widely used and provide a foundation for understanding more complex patterns.

**Q: Where do I find the UML diagrams?**

Each pattern has a class diagram in its `etc/` directory (usually `etc/<pattern-name>.urm.png` or `etc/<pattern-name>.png`).

**Q: How can I contribute a pattern translation?**

Create a directory at `localization/<language-code>/<pattern-name>/`, add a `README.md` following the existing English README structure, and submit a pull request.

**Q: Why is the version `1.26.0-SNAPSHOT`?**

`SNAPSHOT` is Maven's convention for a development version. This is the canonical version of the repository — there are no published releases to Maven Central because this is a learning resource, not a library.

---

_Generated May 2026 from iluwatar/java-design-patterns at 2d39fe7. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
