Behavioral Patterns
Overview
Behavioral patterns focus on communication and responsibility between objects. They help manage control flow and evolving business logic.
Common Behavioral Patterns
- Strategy
- Observer
- Command
- State
- Chain of Responsibility
sequenceDiagram
participant Client
participant Context
participant StrategyA
Client->>Context: execute(request)
Context->>StrategyA: process(request)
StrategyA-->>Context: result
Context-->>Client: result
Practical Example - Strategy
public interface IDiscountStrategy
{
decimal Apply(decimal total);
}
public sealed class LoyaltyDiscount : IDiscountStrategy
{
public decimal Apply(decimal total) => total * 0.90m;
}
Different strategies are selected based on customer segment.
Production Guidance
- Use strategy for variable pricing and policy logic
- Use observer for domain events and notifications
- Use command for auditable operations and retries
Common Pitfalls
- Overusing observer without event ownership rules
- Hiding critical branching logic in too many small classes
- Forgetting idempotency for command retries
Key Takeaways
- Behavioral patterns separate decision logic from orchestration.
- Strategy and command patterns support safer business evolution.
- Event-driven behavior requires ownership and monitoring.