Practical Enum Examples
Payment Method Enum
public enum PaymentMethod {
CREDIT_CARD {
@Override
public void processPayment(double amount) {
System.out.println("Processing credit card payment: $" + amount);
}
},
PAYPAL {
@Override
public void processPayment(double amount) {
System.out.println("Processing PayPal payment: $" + amount);
}
},
BANK_TRANSFER {
@Override
public void processPayment(double amount) {
System.out.println("Processing bank transfer: $" + amount);
}
};
public abstract void processPayment(double amount);
}
User Role Management
public enum UserRole {
ADMIN(3, "Full system access"),
MANAGER(2, "Partial system access"),
USER(1, "Limited access");
private final int accessLevel;
private final String description;
UserRole(int accessLevel, String description) {
this.accessLevel = accessLevel;
this.description = description;
}
public boolean hasAccess(UserRole requiredRole) {
return this.accessLevel >= requiredRole.accessLevel;
}
}
Enum State Machine
stateDiagram-v2
[*] --> PENDING
PENDING --> APPROVED
PENDING --> REJECTED
APPROVED --> COMPLETED
REJECTED --> [*]
COMPLETED --> [*]
Order Status Enum
public enum OrderStatus {
PENDING {
@Override
public boolean canTransitionTo(OrderStatus newStatus) {
return newStatus == APPROVED || newStatus == REJECTED;
}
},
APPROVED {
@Override
public boolean canTransitionTo(OrderStatus newStatus) {
return newStatus == COMPLETED;
}
},
REJECTED,
COMPLETED;
public boolean canTransitionTo(OrderStatus newStatus) {
return false;
}
}
Configuration Settings Enum
public enum AppSettings {
DATABASE_URL("jdbc:mysql://localhost:3306/labex"),
MAX_CONNECTIONS("10"),
LOGGING_LEVEL("INFO");
private final String defaultValue;
AppSettings(String defaultValue) {
this.defaultValue = defaultValue;
}
public String getDefaultValue() {
return defaultValue;
}
}
Enum Comparison Matrix
Enum Type |
Use Case |
Key Benefit |
PaymentMethod |
Payment Processing |
Polymorphic Behavior |
UserRole |
Access Control |
Security Management |
OrderStatus |
Workflow Management |
State Transition Control |
AppSettings |
Configuration Management |
Centralized Settings |
LabEx Design Patterns with Enums
- Strategy Pattern Implementation
- State Machine Modeling
- Configuration Management
- Type-Safe Constant Definitions
Advanced Enum Techniques
public class EnumUtils {
public static <T extends Enum<T>> T findByProperty(
Class<T> enumClass,
Function<T, Boolean> predicate
) {
return Arrays.stream(enumClass.getEnumConstants())
.filter(predicate::apply)
.findFirst()
.orElse(null);
}
}
Best Practices
- Use enums for finite, known set of values
- Implement methods within enum for complex behaviors
- Leverage enum for type safety and readability
- Consider performance and memory implications
By exploring these practical enum examples, developers can unlock powerful design patterns and create more robust Java applications.