design-patterns
/design-patterns
Design patterns with Java examples - classic (Factory, Builder, Strategy, Observer, Decorator, Adapter) and enterprise/microservices (Saga, Outbox, CQRS). Use when user asks about patterns, designing extensible components, or distributed transaction strategies.
- Author
- piomin ↗
- Repository
- claude-ai-quarkus ↗
- Licence
- Apache-2.0
- Last repository change
- 26.10.2026
Assessment and security
- Files in this package
- 1
- Scripts
- 0
- HTML comments
- 0
- URLs in SKILL.md
- 0
No signals detected. Repository changed on 26.10.2026, without references to retired models or APIs.
Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.
What it does and when to use it
Design patterns with Java examples - classic (Factory, Builder, Strategy, Observer, Decorator, Adapter) and enterprise/microservices (Saga, Outbox, CQRS). Use when user asks about patterns, designing extensible components, or distributed transaction strategies.
Original author description
Design patterns with Java examples - classic (Factory, Builder, Strategy, Observer, Decorator, Adapter) and enterprise/microservices (Saga, Outbox, CQRS). Use when user asks about patterns, designing extensible components, or distributed transaction strategies.
How it works
- When to Use
- Quick Reference: When to Use What
- Creational Patterns
- Behavioral Patterns
- Structural Patterns
- Enterprise / Microservices Patterns
- Pattern Selection Guide
- Anti-Patterns to Avoid
SKILL.md preview
---
name: design-patterns
description: Design patterns with Java examples - classic (Factory, Builder, Strategy, Observer, Decorator, Adapter) and enterprise/microservices (Saga, Outbox, CQRS). Use when user asks about patterns, designing extensible components, or distributed transaction strategies.
---
# Design Patterns Skill
Quick reference for common design patterns in Java.
## When to Use
- User asks to implement a specific pattern
- Designing extensible/flexible components
- Refactoring rigid code
## Quick Reference: When to Use What
| Problem | Pattern | Use When |
|---------|---------|----------|
| Complex object construction | **Builder** | Many parameters, some optional |
| Create objects without specifying class | **Factory** | Type determined at runtime |
| Multiple algorithms, swap at runtime | **Strategy** | Behavior varies by context |
| Add behavior without changing class | **Decorator** | Dynamic composition needed |
| Notify multiple objects of changes | **Observer** | One-to-many dependency |
| Convert incompatible interfaces | **Adapter** | Integrate legacy/3rd party code |
| DB update + event publish atomically | **Outbox** | Dual-write problem in microservices |
| Distributed transaction across services | **Saga** | Multi-service business process |
| Separate read/write models | **CQRS** | Heavy read/write ratio skew |
---
## Creational Patterns
### Builder
**Problem:** Telescoping constructors, many optional parameters
```java
// ✅ Builder pattern
public class User {
private final String name; // required
private final String email; // required
private final int age; // optional
private User(Builder builder) {
this.name = builder.name;
this.email = builder.email;
this.age = builder.age;
}
public static Builder builder(String name, String email) {
return new Builder(name, email);
}
public static class Builder {
private final String name;
private final String email;
private int age = 0;
private Builder(String name, String email) {
this.name = name;
this.email = email;
}
public Builder age(int age) {
this.age = age;
return this;
}
public User build() {
return new User(this);
}
}
}
// Usage
User user = User.builder("John", "john@example.com")
.age(30)
.build();
```
### Factory
**Problem:** Create objects without knowing exact class upfront
```java
// ✅ Factory pattern
public interface Notification {
void send(String message);
}
public class NotificationFactory {
public static Notification create(String type) {
return switch (type.toUpperCase()) {
case "EMAIL" -> new EmailNotification();
case "SMS" -> new SmsNotification();
case "PUSH" -> new PushNotification();
default -> throw new IllegalArgumentException("Unknown: " + type);
};
}
}
// CDI version - preferred: collect all implementations of an interface
@ApplicationScoped
public class NotificationFactory {
private final Map<String, NotificationSender> senders;
@Inject
public NotificationFactory(@Any Instance<NotificationSender> senderInstances) {
this.senders = senderInstances.stream()
.collect(Collectors.toMap(
NotificationSender::getType,
Function.identity()
));
}
public NotificationSender get(String type) {
return Optional.ofNullable(senders.get(type))
.orElseThrow(() -> new IllegalArgumentException("Unknown: " + type));
}
}
```
---
## Behavioral Patterns
### Strategy
**Problem:** Multiple algorithms for same operation, choose at runtime
```java
// ✅ Strategy pattern
public interface PaymentStrategy {
void pay(BigDecimal amount);
}
public class CreditCardPayment implements PaymentStrategy {
private final String cardNumber;
public CreditCardPayment(String cardNumber) {
this.cardNumber = cardNumber;
}
@Override
public void pay(BigDecimal amount) {
System.out.println("Paid " + amount + " with card " + cardNumber);
}
}
public class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.paymentStrategy = strategy;
}
public void checkout(BigDecimal total) {
paymentStrategy.pay(total);
}
}
// Usage
cart.setPaymentStrategy(new CreditCardPayment("4111..."));
cart.checkout(new BigDecimal("99.99"));
// Functional variant (Java 8+)
@FunctionalInterface
public interface PaymentStrategy {
void pay(BigDecimal amount);
}
PaymentStrategy creditCard = amount -> System.out.println("Card: " + amount);
cart.setPaymentStrategy(creditCard);
```
### Observer
**Problem:** Notify multiple objects when state changes
```java
// ✅ CDI Events (preferred)
public record OrderPlacedEvent(Order order) {}
@ApplicationScoped
public class OrderService {
@Inject
Event<OrderPlacedEvent> orderPlacedEvent;
public void placeOrder(Order order) {
saveOrder(order);
orderPlacedEvent.fire(new OrderPlacedEvent(order));
}
}
@ApplicationScoped
public class InventoryListener {
public void handleOrderPlaced(@Observes OrderPlacedEvent event) {
// Reduce inventory
}
}
@ApplicationScoped
public class EmailListener {
public void handleOrderPlaced(@ObservesAsync OrderPlacedEvent event) {
// Send email asynchronously (fired with orderPlacedEvent.fireAsync(...))
}
}
```
---
## Structural Patterns
### Decorator
**Problem:** Add behavior dynamically without modifying class
```java
// ✅ Decorator pattern
public interface Coffee {
String getDescription();
BigDecimal getCost();
}
public class SimpleCoffee implements Coffee {
public String getDescription() { return "Coffee"; }
public BigDecimal getCost() { return new BigDecimal("2.00"); }
}
public abstract class CoffeeDecorator implements Coffee {
protected final Coffee coffee;
public CoffeeDecorator(Coffee coffee) { this.coffee = coffee; }
}
public class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) { super(coffee); }
public String getDescription() {
return coffee.getDescription() + ", Milk";
}
public BigDecimal getCost() {
return coffee.getCost().add(new BigDecimal("0.50"));
}
}
// Usage
Coffee coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
```
### Adapter
**Problem:** Make incompatible interfaces work together
```java
// ✅ Adapter pattern
public interface MediaPlayer {
void play(String filename);
}
// Legacy code
public class LegacyAudioPlayer {
public void playMp3(String filename) { /* ... */ }
}
// Adapter
public class Mp3PlayerAdapter implements MediaPlayer {
private final LegacyAudioPlayer legacyPlayer = new LegacyAudioPlayer();
@Override
public void play(String filename) {
legacyPlayer.playMp3(filename);
}
}
// Usage
MediaPlayer player = new Mp3PlayerAdapter();
player.play("song.mp3");
```
---
## Enterprise / Microservices Patterns
### Transactional Outbox
**Problem:** Atomically update database AND publish an event (dual-write problem)
```java
// ✅ Outbox pattern - write event to DB in same transaction, poll and publish later
@Entity
@Table(name = "outbox_events")
public class OutboxEvent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String aggregateType;
private String aggregateId;
private String eventType;
@Column(columnDefinition = "TEXT")
private String payload;
private LocalDateTime createdAt;
private boolean published;
// getters/setters
}
@ApplicationScoped
public class OrderService {
private final OrderRepository orderRepository;
private final OutboxEventRepository outboxRepository;
public OrderService(OrderRepository orderRepository, OutboxEventRepository outboxRepository) {
this.orderRepository = orderRepository;
this.outboxRepository = outboxRepository;
}
@Transactional
public Order createOrder(OrderRequest request) {
Order order = new Order();
order.setStatus(OrderStatus.CREATED);
orderRepository.persist(order);
OutboxEvent event = new OutboxEvent();
event.setAggregateType("Order");
event.setAggregateId(order.getId().toString());
event.setEventType("OrderCreated");
event.setPayload(toJson(order));
event.setCreatedAt(LocalDateTime.now());
event.setPublished(false);
outboxRepository.persist(event);
return order;
}
}
// Poller publishes events and marks them as published
@ApplicationScoped
public class OutboxPoller {
private final OutboxEventRepository outboxRepository;
@Channel("orders")
Emitter<String> ordersEmitter;
public OutboxPoller(OutboxEventRepository outboxRepository) {
this.outboxRepository = outboxRepository;
}
@Scheduled(every = "1s")
@Transactional
public void publishPendingEvents() {
List<OutboxEvent> events = outboxRepository.find("published", false).list();
for (OutboxEvent event : events) {
ordersEmitter.send(event.getPayload());
event.setPublished(true);
}
}
}
```
`@Scheduled` is `io.quarkus.scheduler.Scheduled`; `@Channel`/`Emitter` come from SmallRye Reactive Messaging (`org.eclipse.microprofile.reactive.messaging`), which is also the Quarkus way to publish to Kafka/AMQP without a vendor-specific template class.
### Saga (Choreography)
**Problem:** Distributed transaction across multiple microservices
```java
// ✅ Choreography-based saga - each service listens and reacts
// Order Service publishes OrderCreated
@ApplicationScoped
public class OrderService {
@Inject
Event<OrderCreatedEvent> orderCreatedEvent;
private final OrderRepository orderRepository;
public OrderService(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@Transactional
public Order createOrder(OrderRequest request) {
Order order = new Order();
order.setStatus(OrderStatus.PENDING);
orderRepository.persist(order);
orderCreatedEvent.fire(new OrderCreatedEvent(order.getId(), request.items()));
return order;
}
@Transactional
public void handlePaymentFailed(Long orderId) {
Order order = orderRepository.findByIdOptional(orderId).orElseThrow();
order.setStatus(OrderStatus.CANCELLED);
}
}
// Payment Service listens to OrderCreated via Kafka, publishes PaymentCompleted or PaymentFailed
@ApplicationScoped
public class PaymentEventHandler {
private final PaymentService paymentService;
public PaymentEventHandler(PaymentService paymentService) {
this.paymentService = paymentService;
}
@Incoming("order-events")
public void handleOrderCreated(OrderCreatedEvent event) {
try {
paymentService.charge(event.orderId(), event.amount());
// Publish PaymentCompleted
} catch (PaymentException e) {
// Publish PaymentFailed → triggers compensating action
}
}
}
```
**Choreography vs Orchestration:**
| Aspect | Choreography | Orchestration |
|--------|-------------|---------------|
| Coupling | Low - services react to events | Higher - orchestrator knows all steps |
| Complexity | Hard to trace full flow | Centralized, easier to understand |
| Use when | Few steps, simple flows | Many steps, complex compensation |
### CQRS (Command Query Responsibility Segregation)
**Problem:** Read and write models have different optimization needs
```java
// ✅ CQRS - separate command and query models
// Command side - normalized, validates business rules
@ApplicationScoped
public class OrderCommandService {
private final OrderRepository orderRepository;
@Inject
Event<OrderCreatedEvent> orderCreatedEvent;
public OrderCommandService(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@Transactional
public Long createOrder(CreateOrderCommand command) {
Order order = new Order();
order.setCustomerId(command.customerId());
order.setStatus(OrderStatus.CREATED);
command.items().forEach(order::addItem);
orderRepository.persist(order);
orderCreatedEvent.fire(new OrderCreatedEvent(order));
return order.getId();
}
}
// Query side - denormalized, optimized for reads
@ApplicationScoped
public class OrderQueryService {
private final OrderViewRepository viewRepository;
public OrderQueryService(OrderViewRepository viewRepository) {
this.viewRepository = viewRepository;
}
public OrderView findById(Long id) {
return viewRepository.findByIdOptional(id)
.orElseThrow(() -> new EntityNotFoundException("Order not found"));
}
public List<OrderView> findByCustomer(Long customerId, int pageIndex, int pageSize) {
return viewRepository.find("customerId", customerId)
.page(Page.of(pageIndex, pageSize))
.list();
}
}
// Read model - flat, pre-joined
@Entity
@Table(name = "order_views")
public class OrderView {
@Id
private Long id;
private Long customerId;
private String customerName;
private String status;
private BigDecimal totalAmount;
private int itemCount;
private LocalDateTime createdAt;
// getters/setters
}
// Projection updater - keeps query model in sync
@ApplicationScoped
public class OrderViewUpdater {
private final OrderViewRepository viewRepository;
public OrderViewUpdater(OrderViewRepository viewRepository) {
this.viewRepository = viewRepository;
}
public void on(@Observes OrderCreatedEvent event) {
OrderView view = new OrderView();
view.setId(event.order().getId());
view.setCustomerId(event.order().getCustomerId());
view.setStatus(event.order().getStatus().name());
view.setTotalAmount(event.order().getTotalAmount());
view.setItemCount(event.order().getItems().size());
view.setCreatedAt(event.order().getCreatedAt());
viewRepository.persist(view);
}
}
```
**When to use CQRS:**
- Read/write ratio is heavily skewed (many reads, few writes)
- Read model needs different shape than write model (denormalized views)
- Different scaling requirements for reads vs writes
**When NOT to use:** Simple CRUD applications - adds unnecessary complexity.
---
## Pattern Selection Guide
| Situation | Pattern |
|-----------|---------|
| Object creation is complex | Builder, Factory |
| Need to add features dynamically | Decorator |
| Multiple implementations of algorithm | Strategy |
| React to state changes | Observer (CDI Events) |
| Integrate with legacy code | Adapter |
| Update DB + publish event atomically | Outbox |
| Distributed transaction across services | Saga |
| Separate read/write optimization | CQRS |
## Anti-Patterns to Avoid
| Anti-Pattern | Problem | Better Approach |
|--------------|---------|-----------------|
| Singleton abuse | Global state, hard to test | Dependency Injection (CDI) |
| Factory everywhere | Over-engineering | Simple `new` if type known |
| Deep decorator chains | Hard to debug | Composition, keep chains short |
| CQRS for simple CRUD | Unnecessary complexity | Single model, standard repository |
| Saga without idempotency | Duplicate processing | Idempotent consumers + dedup key |
Versions
| Repository | Score | Licence |
|---|---|---|
| This page · piomin/claude-ai-quarkus | 95 | Apache-2.0 |
| spencerbeggs/effected | 100 | MIT |
| spencerbeggs/effected | 100 | MIT |
| joeblackwaslike/agent-skills | 100 | MIT |
| krzysztofsurdy/code-virtuoso | 100 | MIT |
| nimadorostkar/Claude-Skills-collection | 100 | MIT |
| andreibesleaga/gabbe | 100 | CC-BY-4.0 |
| pantheon-org/tekhne | 100 | MIT |
| itzcull/software-skills | 100 | MIT |
Database snapshot: 13.11.2026 · package version cb8c1885499c (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.
Similar skills
- 95microservice-design-patterns
Use this skill when the user says 'saga pattern', 'distributed transaction', 'compensating transaction', 'choreography vs orchestration', 'CQRS with event sourcing', 'cross-service consistency', 'two-phase commit microservices'. Explains and designs the data-consistency patterns… - 100event-driven
Event-driven architecture patterns and best practices. Covers Saga, Outbox, CQRS, Event Sourcing, and messaging patterns for distributed systems. USE WHEN: user mentions "event-driven", "Saga", "Outbox pattern", "CQRS", "Event Sourcing", "distributed transactions", "eventual… - 90system-design-integration-patterns
Choose distributed integration and evolution patterns by the constraint each removes: outbox, CQRS, event sourcing, saga orchestration or choreography, leader election, sidecar, anti-corruption layer, and strangler-fig migration. Use when services must stay consistent across a boundary. - 100php-patterns
Apply PHP design patterns — Repository, Factory, Strategy, Decorator, Observer, Singleton, Builder, and Dependency Injection patterns in PHP. Use when architecting PHP applications or understanding patterns used in Magento and other frameworks. - 100architecture-patterns
Provides architectural pattern knowledge for designing feature implementations including MVC, event-driven, microservices, and CQRS patterns. Use when designing system architecture or choosing implementation patterns. - 100architecture-patterns
Provides architectural pattern knowledge for designing feature implementations including MVC, event-driven, microservices, and CQRS patterns. Use when designing system architecture or choosing implementation patterns.