Careeroza
Real World Example
Order Status State Machine
Delivery apps like Swiggy move orders through fixed stages and must reject invalid jumps (a delivered order cannot be cancelled). An enum can store the allowed transitions and customer-facing messages.
Example
import java.util.EnumSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Order order = new Order("SW-9012");
order.moveTo(OrderStatus.CONFIRMED);
order.moveTo(OrderStatus.OUT_FOR_DELIVERY);
order.moveTo(OrderStatus.PREPARING);
order.moveTo(OrderStatus.OUT_FOR_DELIVERY);
order.moveTo(OrderStatus.DELIVERED);
order.moveTo(OrderStatus.CANCELLED);
}
}
enum OrderStatus {
PLACED("We have received your order"),
CONFIRMED("Restaurant accepted your order"),
PREPARING("Your food is being prepared"),
OUT_FOR_DELIVERY("Your order is on the way"),
DELIVERED("Enjoy your meal!"),
CANCELLED("Your order was cancelled");
final String message;
OrderStatus(String message) { this.message = message; }
Set<OrderStatus> next() {
return switch (this) {
case PLACED -> EnumSet.of(CONFIRMED, CANCELLED);
case CONFIRMED -> EnumSet.of(PREPARING, CANCELLED);
case PREPARING -> EnumSet.of(OUT_FOR_DELIVERY);
case OUT_FOR_DELIVERY -> EnumSet.of(DELIVERED);
case DELIVERED, CANCELLED -> EnumSet.noneOf(OrderStatus.class);
};
}
}
class Order {
private final String id;
private OrderStatus status = OrderStatus.PLACED;
Order(String id) { this.id = id; }
void moveTo(OrderStatus target) {
if (!status.next().contains(target)) {
System.out.println(id + ": cannot go from " + status + " to " + target);
return;
}
status = target;
System.out.println(id + ": " + status + " - " + status.message);
}
}Output
SW-9012: CONFIRMED - Restaurant accepted your order SW-9012: cannot go from CONFIRMED to OUT_FOR_DELIVERY SW-9012: PREPARING - Your food is being prepared SW-9012: OUT_FOR_DELIVERY - Your order is on the way SW-9012: DELIVERED - Enjoy your meal! SW-9012: cannot go from DELIVERED to CANCELLED
Practice
Exercise: Create an enum Coin with ONE(1), TWO(2), FIVE(5), TEN(10) and a method static int total(Coin... coins) that adds up their values.
Show answer
enum Coin {
ONE(1), TWO(2), FIVE(5), TEN(10);
private final int value;
Coin(int value) { this.value = value; }
static int total(Coin... coins) {
int sum = 0;
for (Coin c : coins) sum += c.value;
return sum;
}
}