行为型模式-状态模式

时间:2024-11-29 17:54:25
// 抽象状态类 public interface OrderState { void handle(); } // 具体状态类:待支付 public class PendingState implements OrderState { @Override public void handle() { System.out.println("订单处于待支付状态。"); } } // 具体状态类:已支付 public class PaidState implements OrderState { @Override public void handle() { System.out.println("订单处于已支付状态。"); } } // 具体状态类:已完成 public class CompletedState implements OrderState { @Override public void handle() { System.out.println("订单已完成。"); } } // 上下文类 public class OrderContext { private OrderState state; // 设置状态 public void setState(OrderState state) { this.state = state; } // 调用当前状态对应的行为 public void handle() { if (state != null) { state.handle(); } } } // 测试 public class Main { public static void main(String[] args) { OrderContext context = new OrderContext(); // 设置为待支付状态 context.setState(new PendingState()); context.handle(); // 设置为已支付状态 context.setState(new PaidState()); context.handle(); // 设置为已完成状态 context.setState(new CompletedState()); context.handle(); } }