本文节选自《设计模式就该这样学》
1 状态模式的 UML 类图
状态模式的 UML 类图如下图所示。
2 应用状态模式实现登录状态自在切换
当咱们在社区阅读文章时,如果感觉文章写得很好,咱们就会评论、珍藏两连发。如果处于登录状况下,则能够间接做评论、珍藏这些行为。否则,跳转到登录界面,登录后再继续执行先前的动作。这里波及的状态有两种:登录与未登录;行为有两种:评论和珍藏。上面应用状态模式来实现这个逻辑,代码如下。
首先创立形象状态角色 UserState 类。
public abstract class UserState {
protected AppContext context;
public void setContext(AppContext context) {this.context = context;}
public abstract void favorite();
public abstract void comment(String comment);
}
而后创立登录状态 LogInState 类。
public class LoginInState extends UserState {
@Override
public void favorite() {System.out.println("珍藏胜利!");
}
@Override
public void comment(String comment) {System.out.println(comment);
}
}
创立未登录状态 UnloginState 类。
public class UnLoginState extends UserState {
@Override
public void favorite() {this.switch2Login();
this.context.getState().favorite();
}
@Override
public void comment(String comment) {this.switch2Login();
this.context.getState().comment(comment);
}
private void switch2Login() {System.out.println("跳转到登录页面!");
this.context.setState(this.context.STATE_LOGIN);
}
}
创立上下文角色 AppContext 类。
public class AppContext {public static final UserState STATE_LOGIN = new LoginInState();
public static final UserState STATE_UNLOGIN = new UnLoginState();
private UserState currentState = STATE_UNLOGIN;
{STATE_LOGIN.setContext(this);
STATE_UNLOGIN.setContext(this);
}
public void setState(UserState state) {
this.currentState = state;
this.currentState.setContext(this);
}
public UserState getState() {return this.currentState;}
public void favorite() {this.currentState.favorite();
}
public void comment(String comment) {this.currentState.comment(comment);
}
}
最初编写客户端测试代码。
public static void main(String[] args) {AppContext context = new AppContext();
context.favorite();
context.comment("评论: 好文章,360 个赞!");
}
运行后果如下图所示。
3 应用状态机实现订单状态流转管制
状态机是状态模式的一种利用,相当于上下文角色的一个升级版。在工作流或游戏等各种零碎中有大量应用,如各种工作流引擎,它简直是状态机的子集和实现,封装状态的变动规定。Spring 也提供了一个很好的解决方案。Spring 中的组件名称就叫作状态机(StateMachine)。状态机帮忙开发者简化状态管制的开发过程,让状态机构造更加层次化。上面用 Spring 状态机模仿一个订单状态流转的过程。
3.1 增加依赖。
<dependency>
<groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-core</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
3.2 创立订单实体 Order 类。
public class Order {
private int id;
private OrderStatus status;
public void setStatus(OrderStatus status) {this.status = status;}
public OrderStatus getStatus() {return status;}
public void setId(int id) {this.id = id;}
public int getId() {return id;}
@Override
public String toString() {return "订单号:" + id + ", 订单状态:" + status;}
}
3.3 创立订单状态枚举类和状态转换枚举类。
/**
* 订单状态
*/
public enum OrderStatus {
// 待领取,待发货,待收货,订单完结
WAIT_PAYMENT, WAIT_DELIVER, WAIT_RECEIVE, FINISH;
}
/**
* 订单状态扭转事件
*/
public enum OrderStatusChangeEvent {
// 领取,发货,确认收货
PAYED, DELIVERY, RECEIVED;
}
3.4 增加状态流转配置。
/**
* 订单状态机配置
*/
@Configuration
@EnableStateMachine(name = "orderStateMachine")
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderStatus, OrderStatusChangeEvent> {
/**
* 配置状态
* @param states
* @throws Exception
*/
public void configure(StateMachineStateConfigurer<OrderStatus, OrderStatusChangeEvent> states) throws Exception {
states
.withStates()
.initial(OrderStatus.WAIT_PAYMENT)
.states(EnumSet.allOf(OrderStatus.class));
}
/**
* 配置状态转换事件关系
* @param transitions
* @throws Exception
*/
public void configure(StateMachineTransitionConfigurer<OrderStatus, OrderStatusChangeEvent> transitions) throws Exception {
transitions
.withExternal().source(OrderStatus.WAIT_PAYMENT).target(OrderStatus.WAIT_DELIVER)
.event(OrderStatusChangeEvent.PAYED)
.and()
.withExternal().source(OrderStatus.WAIT_DELIVER).target(OrderStatus.WAIT_RECEIVE)
.event(OrderStatusChangeEvent.DELIVERY)
.and()
.withExternal().source(OrderStatus.WAIT_RECEIVE).target(OrderStatus.FINISH)
.event(OrderStatusChangeEvent.RECEIVED);
}
/**
* 长久化配置
* 在理论应用中,能够配合 Redis 等进行长久化操作
* @return
*/
@Bean
public DefaultStateMachinePersister persister(){return new DefaultStateMachinePersister<>(new StateMachinePersist<Object, Object, Order>() {
@Override
public void write(StateMachineContext<Object, Object> context, Order order) throws Exception {// 此处并没有进行长久化操作}
@Override
public StateMachineContext<Object, Object> read(Order order) throws Exception {
// 此处间接获取 Order 中的状态,其实并没有进行长久化读取操作
return new DefaultStateMachineContext(order.getStatus(), null, null, null);
}
});
}
}
3.5 增加订单状态监听器。
@Component("orderStateListener")
@WithStateMachine(name = "orderStateMachine")
public class OrderStateListenerImpl{@OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER")
public boolean payTransition(Message<OrderStatusChangeEvent> message) {Order order = (Order) message.getHeaders().get("order");
order.setStatus(OrderStatus.WAIT_DELIVER);
System.out.println("领取,状态机反馈信息:" + message.getHeaders().toString());
return true;
}
@OnTransition(source = "WAIT_DELIVER", target = "WAIT_RECEIVE")
public boolean deliverTransition(Message<OrderStatusChangeEvent> message) {Order order = (Order) message.getHeaders().get("order");
order.setStatus(OrderStatus.WAIT_RECEIVE);
System.out.println("发货,状态机反馈信息:" + message.getHeaders().toString());
return true;
}
@OnTransition(source = "WAIT_RECEIVE", target = "FINISH")
public boolean receiveTransition(Message<OrderStatusChangeEvent> message){Order order = (Order) message.getHeaders().get("order");
order.setStatus(OrderStatus.FINISH);
System.out.println("收货,状态机反馈信息:" + message.getHeaders().toString());
return true;
}
}
3.6 创立 IOrderService 接口。
public interface IOrderService {
// 创立新订单
Order create();
// 发动领取
Order pay(int id);
// 订单发货
Order deliver(int id);
// 订单收货
Order receive(int id);
// 获取所有订单信息
Map<Integer, Order> getOrders();}
3.7 在 Service 业务逻辑中利用。
@Service("orderService")
public class OrderServiceImpl implements IOrderService {
@Autowired
private StateMachine<OrderStatus, OrderStatusChangeEvent> orderStateMachine;
@Autowired
private StateMachinePersister<OrderStatus, OrderStatusChangeEvent, Order> persister;
private int id = 1;
private Map<Integer, Order> orders = new HashMap<>();
public Order create() {Order order = new Order();
order.setStatus(OrderStatus.WAIT_PAYMENT);
order.setId(id++);
orders.put(order.getId(), order);
return order;
}
public Order pay(int id) {Order order = orders.get(id);
System.out.println("线程名称:" + Thread.currentThread().getName() + "尝试领取,订单号:" + id);
Message message = MessageBuilder.withPayload(OrderStatusChangeEvent.PAYED).
setHeader("order", order).build();
if (!sendEvent(message, order)) {System.out.println("线程名称:" + Thread.currentThread().getName() + "领取失败, 状态异样,订单号:" + id);
}
return orders.get(id);
}
public Order deliver(int id) {Order order = orders.get(id);
System.out.println("线程名称:" + Thread.currentThread().getName() + "尝试发货,订单号:" + id);
if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEvent.DELIVERY)
.setHeader("order", order).build(), orders.get(id))) {System.out.println("线程名称:" + Thread.currentThread().getName() + "发货失败,状态异样,订单号:" + id);
}
return orders.get(id);
}
public Order receive(int id) {Order order = orders.get(id);
System.out.println("线程名称:" + Thread.currentThread().getName() + "尝试收货,订单号:" + id);
if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEvent.RECEIVED)
.setHeader("order", order).build(), orders.get(id))) {System.out.println("线程名称:" + Thread.currentThread().getName() + "收货失败,状态异样,订单号:" + id);
}
return orders.get(id);
}
public Map<Integer, Order> getOrders() {return orders;}
/**
* 发送订单状态转换事件
*
* @param message
* @param order
* @return
*/
private synchronized boolean sendEvent(Message<OrderStatusChangeEvent> message, Order order) {
boolean result = false;
try {orderStateMachine.start();
// 尝试复原状态机状态
persister.restore(orderStateMachine, order);
// 增加提早用于线程平安测试
Thread.sleep(1000);
result = orderStateMachine.sendEvent(message);
// 长久化状态机状态
persister.persist(orderStateMachine, order);
} catch (Exception e) {e.printStackTrace();
} finally {orderStateMachine.stop();
}
return result;
}
}
3.8 编写客户端测试代码。
@SpringBootApplication
public class Test {public static void main(String[] args) {Thread.currentThread().setName("主线程");
ConfigurableApplicationContext context = SpringApplication.run(Test.class,args);
IOrderService orderService = (IOrderService)context.getBean("orderService");
orderService.create();
orderService.create();
orderService.pay(1);
new Thread("客户线程"){
@Override
public void run() {orderService.deliver(1);
orderService.receive(1);
}
}.start();
orderService.pay(2);
orderService.deliver(2);
orderService.receive(2);
System.out.println("全副订单状态:" + orderService.getOrders());
}
}
通过这个实在的业务案例,置信小伙伴们曾经对状态模式有了一个十分粗浅的了解。
关注微信公众号『Tom 弹架构』回复“设计模式”可获取残缺源码。
【举荐】Tom 弹架构:30 个设计模式实在案例(附源码),挑战年薪 60W 不是梦
本文为“Tom 弹架构”原创,转载请注明出处。技术在于分享,我分享我高兴!
如果本文对您有帮忙,欢送关注和点赞;如果您有任何倡议也可留言评论或私信,您的反对是我保持创作的能源。关注微信公众号『Tom 弹架构』可获取更多技术干货!