1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
|
public class StateMachineFramework {
public interface State { String getName(); void onEnter(StateMachineContext context); void onExit(StateMachineContext context); void onEvent(StateMachineContext context, Event event); }
public interface Event { String getName(); Object getData(); }
public static class StateMachineContext { private Object entity; private Map<String, Object> variables; private StateMachine stateMachine; public StateMachineContext(Object entity, StateMachine stateMachine) { this.entity = entity; this.stateMachine = stateMachine; this.variables = new HashMap<>(); } public Object getEntity() { return entity; } public StateMachine getStateMachine() { return stateMachine; } public Map<String, Object> getVariables() { return variables; } public void setVariable(String key, Object value) { variables.put(key, value); } public Object getVariable(String key) { return variables.get(key); } }
public static class StateMachine { private Map<String, State> states; private Map<String, Map<String, State>> transitions; private State currentState; private StateMachineContext context; public StateMachine() { this.states = new HashMap<>(); this.transitions = new HashMap<>(); } public void addState(State state) { states.put(state.getName(), state); } public void addTransition(String fromState, String event, String toState) { transitions.computeIfAbsent(fromState, k -> new HashMap<>()).put(event, states.get(toState)); } public void setInitialState(String stateName) { this.currentState = states.get(stateName); if (currentState != null) { currentState.onEnter(context); } } public void setContext(StateMachineContext context) { this.context = context; } public boolean canTransition(String event) { if (currentState == null) return false; Map<String, State> stateTransitions = transitions.get(currentState.getName()); return stateTransitions != null && stateTransitions.containsKey(event); } public boolean transition(String event) { if (!canTransition(event)) { return false; } State nextState = transitions.get(currentState.getName()).get(event); if (nextState != null) { currentState.onExit(context); currentState = nextState; currentState.onEnter(context); return true; } return false; } public void processEvent(Event event) { if (currentState != null) { currentState.onEvent(context, event); } } public State getCurrentState() { return currentState; } public String getCurrentStateName() { return currentState != null ? currentState.getName() : null; } } }
public class OrderStateMachine {
public enum OrderState { PENDING("待处理"), CONFIRMED("已确认"), PAID("已支付"), SHIPPED("已发货"), DELIVERED("已送达"), CANCELLED("已取消"), REFUNDED("已退款"); private final String description; OrderState(String description) { this.description = description; } public String getDescription() { return description; } }
public enum OrderEvent { CONFIRM("确认订单"), PAY("支付"), SHIP("发货"), DELIVER("送达"), CANCEL("取消"), REFUND("退款"); private final String description; OrderEvent(String description) { this.description = description; } public String getDescription() { return description; } }
public static class OrderStateImpl implements StateMachineFramework.State { private OrderState orderState; public OrderStateImpl(OrderState orderState) { this.orderState = orderState; } @Override public String getName() { return orderState.name(); } @Override public void onEnter(StateMachineFramework.StateMachineContext context) { Order order = (Order) context.getEntity(); order.setState(orderState); System.out.println("订单 " + order.getId() + " 进入状态: " + orderState.getDescription()); } @Override public void onExit(StateMachineFramework.StateMachineContext context) { Order order = (Order) context.getEntity(); System.out.println("订单 " + order.getId() + " 离开状态: " + orderState.getDescription()); } @Override public void onEvent(StateMachineFramework.StateMachineContext context, StateMachineFramework.Event event) { Order order = (Order) context.getEntity(); System.out.println("订单 " + order.getId() + " 在状态 " + orderState.getDescription() + " 处理事件: " + event.getName()); } }
public static class OrderEventImpl implements StateMachineFramework.Event { private OrderEvent orderEvent; private Object data; public OrderEventImpl(OrderEvent orderEvent, Object data) { this.orderEvent = orderEvent; this.data = data; } @Override public String getName() { return orderEvent.name(); } @Override public Object getData() { return data; } }
public static class OrderStateMachineBuilder { private StateMachineFramework.StateMachine stateMachine; public OrderStateMachineBuilder() { this.stateMachine = new StateMachineFramework.StateMachine(); } public OrderStateMachineBuilder addStates() { for (OrderState state : OrderState.values()) { stateMachine.addState(new OrderStateImpl(state)); } return this; } public OrderStateMachineBuilder addTransitions() { stateMachine.addTransition("PENDING", "CONFIRM", "CONFIRMED"); stateMachine.addTransition("PENDING", "CANCEL", "CANCELLED"); stateMachine.addTransition("CONFIRMED", "PAY", "PAID"); stateMachine.addTransition("CONFIRMED", "CANCEL", "CANCELLED"); stateMachine.addTransition("PAID", "SHIP", "SHIPPED"); stateMachine.addTransition("PAID", "REFUND", "REFUNDED"); stateMachine.addTransition("SHIPPED", "DELIVER", "DELIVERED"); stateMachine.addTransition("DELIVERED", "REFUND", "REFUNDED"); return this; } public StateMachineFramework.StateMachine build() { return stateMachine; } } }
public class Order extends Entity<OrderId> { private OrderState state; private String customerId; private List<OrderItem> items; private Money totalAmount; private Address shippingAddress; private PaymentInfo paymentInfo; private StateMachineFramework.StateMachine stateMachine; public Order(OrderId id, String customerId, List<OrderItem> items, Address shippingAddress) { super(id); this.customerId = customerId; this.items = items; this.shippingAddress = shippingAddress; this.state = OrderState.PENDING; this.totalAmount = calculateTotalAmount(); initializeStateMachine(); } private void initializeStateMachine() { this.stateMachine = new OrderStateMachine.OrderStateMachineBuilder() .addStates() .addTransitions() .build(); StateMachineFramework.StateMachineContext context = new StateMachineFramework.StateMachineContext(this, stateMachine); stateMachine.setContext(context); stateMachine.setInitialState("PENDING"); } public void confirm() { if (stateMachine.canTransition("CONFIRM")) { stateMachine.transition("CONFIRM"); } else { throw new InvalidStateTransitionException("Cannot confirm order in current state: " + state); } } public void pay(PaymentInfo paymentInfo) { if (stateMachine.canTransition("PAY")) { this.paymentInfo = paymentInfo; stateMachine.transition("PAY"); } else { throw new InvalidStateTransitionException("Cannot pay order in current state: " + state); } } public void ship(String trackingNumber) { if (stateMachine.canTransition("SHIP")) { stateMachine.setVariable("trackingNumber", trackingNumber); stateMachine.transition("SHIP"); } else { throw new InvalidStateTransitionException("Cannot ship order in current state: " + state); } } public void deliver() { if (stateMachine.canTransition("DELIVER")) { stateMachine.transition("DELIVER"); } else { throw new InvalidStateTransitionException("Cannot deliver order in current state: " + state); } } public void cancel(String reason) { if (stateMachine.canTransition("CANCEL")) { stateMachine.setVariable("cancelReason", reason); stateMachine.transition("CANCEL"); } else { throw new InvalidStateTransitionException("Cannot cancel order in current state: " + state); } } public void refund(String reason) { if (stateMachine.canTransition("REFUND")) { stateMachine.setVariable("refundReason", reason); stateMachine.transition("REFUND"); } else { throw new InvalidStateTransitionException("Cannot refund order in current state: " + state); } } private Money calculateTotalAmount() { return items.stream() .map(OrderItem::getSubtotal) .reduce(Money.ZERO, Money::add); } public OrderState getState() { return state; } public void setState(OrderState state) { this.state = state; } public String getCustomerId() { return customerId; } public List<OrderItem> getItems() { return items; } public Money getTotalAmount() { return totalAmount; } public Address getShippingAddress() { return shippingAddress; } public PaymentInfo getPaymentInfo() { return paymentInfo; } }
public class OrderId extends ValueObject { private String value; public OrderId(String value) { this.value = value; } public String getValue() { return value; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; OrderId orderId = (OrderId) obj; return Objects.equals(value, orderId.value); } @Override public int hashCode() { return Objects.hash(value); } }
public class OrderItem extends Entity<OrderItemId> { private String productId; private String productName; private int quantity; private Money unitPrice; public OrderItem(OrderItemId id, String productId, String productName, int quantity, Money unitPrice) { super(id); this.productId = productId; this.productName = productName; this.quantity = quantity; this.unitPrice = unitPrice; } public Money getSubtotal() { return unitPrice.multiply(quantity); } public String getProductId() { return productId; } public String getProductName() { return productName; } public int getQuantity() { return quantity; } public Money getUnitPrice() { return unitPrice; } }
public class OrderItemId extends ValueObject { private String value; public OrderItemId(String value) { this.value = value; } public String getValue() { return value; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; OrderItemId orderItemId = (OrderItemId) obj; return Objects.equals(value, orderItemId.value); } @Override public int hashCode() { return Objects.hash(value); } }
public class Money extends ValueObject { public static final Money ZERO = new Money(0, "CNY"); private long amount; private String currency; public Money(long amount, String currency) { this.amount = amount; this.currency = currency; } public Money add(Money other) { if (!currency.equals(other.currency)) { throw new IllegalArgumentException("Cannot add different currencies"); } return new Money(amount + other.amount, currency); } public Money subtract(Money other) { if (!currency.equals(other.currency)) { throw new IllegalArgumentException("Cannot subtract different currencies"); } return new Money(amount - other.amount, currency); } public Money multiply(int multiplier) { return new Money(amount * multiplier, currency); } public double getAmount() { return amount / 100.0; } public String getCurrency() { return currency; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Money money = (Money) obj; return amount == money.amount && Objects.equals(currency, money.currency); } @Override public int hashCode() { return Objects.hash(amount, currency); } @Override public String toString() { return String.format("%.2f %s", getAmount(), currency); } }
public class PaymentInfo extends ValueObject { private String paymentMethod; private String transactionId; private Money amount; private long timestamp; public PaymentInfo(String paymentMethod, String transactionId, Money amount) { this.paymentMethod = paymentMethod; this.transactionId = transactionId; this.amount = amount; this.timestamp = System.currentTimeMillis(); } public String getPaymentMethod() { return paymentMethod; } public String getTransactionId() { return transactionId; } public Money getAmount() { return amount; } public long getTimestamp() { return timestamp; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; PaymentInfo that = (PaymentInfo) obj; return timestamp == that.timestamp && Objects.equals(paymentMethod, that.paymentMethod) && Objects.equals(transactionId, that.transactionId) && Objects.equals(amount, that.amount); } @Override public int hashCode() { return Objects.hash(paymentMethod, transactionId, amount, timestamp); } }
|