我们知道Java里共有23种设计模式,允许对象在内部状态发生改变时改变它的行为,状态模式属于行为型设计模式。
状态模式
定义
状态模式也称为状态机模式,是允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。
适用场景
(1) 行为随着状态的改变而改变的场景。
(2) 一个操作中含有庞大的多分支结构,并且这些分支取决于对象的状态。
优点
(1) 结构清晰,将状态独立为类,消除了冗余的if...else语句,使代码更加简洁,提高系统可维护性。
(2) 将状态转换显示化,通常的对象内部都是使用数值类型来定义状态,状态的切换是通过赋值进行表现,不够直观,而使用状态类,在切换状态时,是以不同的类进行表示,转换目的更加明确。
(3) 状态类职责明确且具有扩展性。
缺点
(1) 类膨胀,如果一个事物具备很多状态,则会造成状态类太多。
(2) 状态模式的结构与实现都较为复杂,如果使用不当将导致程序结构和代码混乱
(3) 状态模式对开闭原则的支持并不友好,对于可以切换状态的状态模式,增加新的状态类需要修改那些负责状态转换的源代码,否则无法切换到新增状态,而且修改某个状态类的行为也需要修改对应类的源代码。
实例
Maven依赖
org.springframework.statemachine
spring-statemachine-core
2.0.1.RELEASE
创建订单实体
/**
* 创建订单实体类
*/
public class Order {
private int id;
private OrderStatus status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public OrderStatus getStatus() {
return status;
}
public void setStatus(OrderStatus status) {
this.status = status;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", status=" + status +
'}';
}
}
创建订单状态枚举类
/**
* 订单状态枚举类
*/
public enum OrderStatus {
//待支付,待发货,待收货,订单结束
WAIT_PAYMENT, WAIT_DELIVER, WAIT_RECEIVE, FINISH;
}
创建订单状态转换枚举类
/**
* 订单状态转换枚举类
*/
public enum OrderStatusChangeEvent {
//支付,发货,确认收货
PAYED,DELIVERY,RECEIVED;
}
添加状态流转配置
/**
* 订单状态机配置
*/
@Configuration
@EnableStateMachine(name = "orderStateMachine")
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter {
/**
* @title 配置状态
*
* @param states
* @return
*/
@Override
public void configure(StateMachineStateConfigurer states) throws Exception {
states.withStates().initial(OrderStatus.WAIT_PAYMENT).states(EnumSet.allOf(OrderStatus.class));
}
/**
* @title 配置状态转换事件关系
*
* @param transitions
* @return
*/
@Override
public void configure(StateMachineTransitionConfigurer 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);
}
/**
* @title 持久化配置, 实际使用中可以配合redis等进行持久化操作
*
* @param
* @return
*/
@Bean
public DefaultStateMachinePersister persister() {
return new DefaultStateMachinePersister<>(new StateMachinePersist
添加订单状态监听器
/**
* 添加订单状态监听器
*/
@Component("orderStateListener")
@WithStateMachine(name = "orderStateMachine")
public class OrderStateListenerImpl {
@OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER")
public boolean payTransition(Message 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 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 message) {
Order order = (Order) message.getHeaders().get("order");
order.setStatus(OrderStatus.FINISH);
System.out.println("收货,状态机返回信息:" + message.getHeaders().toString());
return true;
}
}
创建IOrderService接口
/**
* 创建IOrderService接口
*/
public interface IOrderService {
/**
* 创建新订单
*/
Order create();
/**
* 发起支付
*/
Order pay(int id);
/**
* 订单发货
*/
Order deliver(int id);
/**
* 订单收货
*/
Order receive(int id);
/**
* 获取所有订单信息
*/
Map getOrders();
}
创建业务逻辑
/**
* 业务逻辑
*/
@Service("orderService")
public class OrderServiceImpl implements IOrderService {
@Autowired
private StateMachine orderStateMachine;
@Autowired
private StateMachinePersister persister;
private int id = 1;
private Map orders = new HashMap<>();
@Override
public Order create() {
Order order = new Order();
order.setStatus(OrderStatus.WAIT_PAYMENT);
order.setId(id++);
orders.put(order.getId(), order);
return order;
}
@Override
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);
}
@Override
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);
}
@Override
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);
}
@Override
public Map getOrders() {
return orders;
}
/**
* @title 发送订单状态转换事件
*
* @param message
* @param order
* @return
*/
private synchronized boolean sendEvent(Message 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;
}
}
测试类
/**
* 测试类
*/
@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());
}
}