State Design Pattern in Java
Learn State Design Pattern in Java with workflow state transitions, order lifecycle management, loan processing workflows, Spring State Machine, UML diagrams, code examples, enterprise use cases, and interview questions.
What You Will Learn
- What is State Pattern?
- Why State Pattern is Needed
- State Transitions
- Workflow Engines
- Order Processing States
- Loan Processing States
- Java Implementation
- Spring State Machine
- Enterprise Use Cases
- Benefits and Limitations
- Interview Questions
Introduction
Many enterprise systems are state-driven.
Examples:
Order Created
Payment Completed
Order Shipped
Order Delivered
Or:
Loan Submitted
Under Review
Approved
Rejected
Or:
Claim Submitted
Investigation
Approval
Settlement
Objects behave differently depending on their current state.
State Pattern helps manage this behavior cleanly.
What is State Pattern?
State is a Behavioral Design Pattern that allows an object to change its behavior when its internal state changes.
Simple View:
Current State
↓
Action
↓
Next State
The object appears to change its class behavior dynamically.
Purpose of State Pattern
Primary goal:
Encapsulate State Specific Behavior
And
Avoid Large If Else Blocks
Real World Analogy
Traffic Signal.
Current State:
Red
Action:
Wait
Next State:
Green
Behavior changes depending on current state.
Problem Without State Pattern
if(state.equals("NEW")) {
}
else if(state.equals("PROCESSING")) {
}
else if(state.equals("SHIPPED")) {
}
else if(state.equals("DELIVERED")) {
}
Problems:
Too Many Conditions
Hard Maintenance
Difficult Extension
Solution With State Pattern
flowchart LR
A[New]
B[Processing]
C[Shipped]
D[Delivered]
A --> B
B --> C
C --> D
Each state has its own behavior.
State Pattern Architecture
flowchart LR
A[Context]
B[State Interface]
C[Concrete State A]
D[Concrete State B]
A --> B
B --> C
B --> D
Key Components
Context
Maintains current state.
State
Defines state behavior.
Concrete State
Implements state-specific behavior.
UML Diagram
classDiagram
class State {
+handle()
}
class NewState
class ProcessingState
class DeliveredState
State <|.. NewState
State <|.. ProcessingState
State <|.. DeliveredState
Order Processing Example
Order Lifecycle:
NEW
↓
PROCESSING
↓
SHIPPED
↓
DELIVERED
State Transition Flow
flowchart LR
A[New]
B[Processing]
C[Shipped]
D[Delivered]
A --> B
B --> C
C --> D
Step 1: State Interface
public interface OrderState {
void processOrder(
OrderContext context);
}
Step 2: New State
public class NewState
implements OrderState {
@Override
public void processOrder(
OrderContext context) {
System.out.println(
"Order Processing Started");
context.setState(
new ProcessingState());
}
}
Step 3: Processing State
public class ProcessingState
implements OrderState {
@Override
public void processOrder(
OrderContext context) {
System.out.println(
"Order Shipped");
context.setState(
new ShippedState());
}
}
Step 4: Shipped State
public class ShippedState
implements OrderState {
@Override
public void processOrder(
OrderContext context) {
System.out.println(
"Order Delivered");
context.setState(
new DeliveredState());
}
}
Step 5: Delivered State
public class DeliveredState
implements OrderState {
@Override
public void processOrder(
OrderContext context) {
System.out.println(
"Order Completed");
}
}
Step 6: Context
public class OrderContext {
private OrderState state;
public OrderContext() {
state = new NewState();
}
public void setState(
OrderState state) {
this.state = state;
}
public void processOrder() {
state.processOrder(this);
}
}
Step 7: Client
public class StateDemo {
public static void main(
String[] args) {
OrderContext order =
new OrderContext();
order.processOrder();
order.processOrder();
order.processOrder();
order.processOrder();
}
}
Output
Order Processing Started
Order Shipped
Order Delivered
Order Completed
Execution Flow
sequenceDiagram
Client->>NewState: process()
NewState->>ProcessingState: transition()
ProcessingState->>ShippedState: transition()
ShippedState->>DeliveredState: transition()
Banking Example
Loan Workflow:
Submitted
Under Review
Approved
Disbursed
Banking State Flow
flowchart LR
A[Submitted]
B[Review]
C[Approved]
D[Disbursed]
A --> B
B --> C
C --> D
Insurance Example
Claim Workflow:
Claim Submitted
Verification
Approval
Settlement
Insurance State Flow
flowchart LR
A[Claim Submitted]
B[Verification]
C[Approval]
D[Settlement]
A --> B
B --> C
C --> D
ATM Machine Example
ATM States:
No Card
Card Inserted
Pin Verified
Transaction Processing
Behavior changes depending on state.
ATM Workflow
flowchart LR
A[No Card]
B[Card Inserted]
C[Pin Verified]
D[Transaction]
A --> B
B --> C
C --> D
Spring State Machine
Spring provides:
spring-statemachine
For complex workflow management.
Example States
public enum States {
NEW,
PROCESSING,
SHIPPED,
DELIVERED
}
Example Events
public enum Events {
PROCESS,
SHIP,
DELIVER
}
Spring Workflow
flowchart LR
A[State Machine]
B[Event]
C[State Change]
A --> B
B --> C
Microservices Example
Order Service State Changes:
Order Created
Payment Received
Inventory Reserved
Shipment Created
Delivered
Each event triggers a state transition.
Kafka Workflow
flowchart LR
A[Order Created]
B[Payment Event]
C[Inventory Event]
D[Shipping Event]
E[Delivered Event]
A --> B
B --> C
C --> D
D --> E
Enterprise Examples
Banking
Loan Processing
KYC Verification
Account Opening
Insurance
Claim Lifecycle
Policy Approval
Retail
Order Processing
Shipment Tracking
Healthcare
Patient Registration
Diagnosis
Treatment
Discharge
Benefits
✅ Eliminates Large If-Else Blocks
✅ Better Maintainability
✅ Easier State Transitions
✅ Supports Workflow Engines
✅ Follows Open Closed Principle
✅ State Logic Is Isolated
Limitations
❌ More Classes
❌ Slightly Higher Complexity
❌ Overkill For Simple States
When To Use
Use State Pattern when:
- Object behavior changes based on state
- Complex workflows exist
- State transitions are frequent
- Large conditional logic exists
When Not To Use
Avoid when:
- Only a few simple states exist
- State changes are rare
State vs Strategy
| Feature | State | Strategy |
|---|---|---|
| Purpose | State Transitions | Algorithm Selection |
| Behavior | Changes Automatically | Selected By Client |
| Example | Order Lifecycle | Payment Strategy |
State vs Observer
| Feature | State | Observer |
|---|---|---|
| Focus | Internal State | Notifications |
| Trigger | State Change | Event Change |
| Example | Workflow Engine | Event Bus |
Real Enterprise Architecture
flowchart LR
A[Application]
B[State Machine]
C[Workflow Engine]
D[Business Process]
A --> B
B --> C
C --> D
Interview Questions
What is State Pattern?
A behavioral pattern that allows objects to change behavior based on current state.
Main Components?
Context
State
Concrete State
Real World Example?
Traffic Signals.
Enterprise Example?
Loan Processing Workflow.
Spring Example?
Spring State Machine.
Main Benefit?
Eliminates complex conditional logic.
Difference Between State and Strategy?
State changes behavior automatically based on transitions, while Strategy is chosen externally.
Key Takeaways
- State is a Behavioral Design Pattern.
- Encapsulates state-specific behavior.
- Eliminates large conditional blocks.
- Common in workflow engines.
- Widely used in Banking, Insurance, Retail, and Healthcare systems.
- Spring State Machine is a real-world implementation.
- Ideal for lifecycle management and state transitions.