设计模式——状态模式(State Pattern)

状态模式(State Pattern)又称状态机模式,是允许对象在内部状态发生改变时改变他的的行为,类的行为由状态决定,不同的状态有着不同的行为,对象看起来好像修改了它的类。属于行为型模式。

一般涉及到电商订单相关的,会采用状态模式来设计,不同的订单状态,响应的都有不同的操作。

适用场景

1) 行为随状态改变而改变的场景
2) 一个操作中含有庞大的多分支结构,并且这些分支取决于对象的状态

主要设计结构图

设计模式——状态模式(State Pattern)_第1张图片

代码演示

状态抽象对象

public abstract class State {
    private AppContext context;
    public void setContext(AppContext context) {
        this.context = context;
    }
    public AppContext getContext() {
        return context;
    }

    abstract void favourite();
    abstract void updatePwd();
}

具体不同状态

public class GuestState extends State {
    @Override
    void favourite() {
        forwardToLoginPage();
        this.getContext().favourite();
    }

    @Override
    void updatePwd() {
        forwardToLoginPage();
        this.getContext().updatePwd();
    }

    private void forwardToLoginPage() {
        System.out.println("跳转到登陆页面");
        this.getContext().setState(AppContext.STATE_LOGIN);
    }
}
public class LoginState extends State {
    @Override
    void favourite() {
        System.out.println("登陆成功,跳转到首页");
        System.out.println("收藏成功!");
    }

    @Override
    void updatePwd() {
        System.out.println("修改安全信息,需要再次验证您的身份!");
        this.getContext().setState(AppContext.STATE_REAUTH);
        this.getContext().updatePwd();
    }
}
public class ReauthState extends State {
    @Override
    void favourite() {
        System.out.println("收藏成功!");
    }

    @Override
    void updatePwd() {
        System.out.println("密码修改成功!");
    }
}

上下文对象

public class AppContext {
    protected static final State STATE_GUEST = new GuestState();
    protected static final State STATE_LOGIN = new LoginState();
    protected static final State STATE_REAUTH = new ReauthState();
    private State currentSate = STATE_GUEST;

    {
        STATE_GUEST.setContext(this);
        STATE_LOGIN.setContext(this);
        STATE_REAUTH.setContext(this);
    }

    public void setState(State state) {
        this.currentSate = state;
    }

    public void favourite() {
        this.currentSate.favourite();
    }
    public void updatePwd() {
        this.currentSate.updatePwd();
    }
}

测试类

public class Test {
    public static void main(String[] args) {
        AppContext context = new AppContext();
        context.favourite();
        context.updatePwd();
    }
}

执行结果

跳转到登陆页面
登陆成功,跳转到首页
收藏成功!
修改安全信息,需要再次验证您的身份!
密码修改成功!

Spring中状态模式的应用:StateMachine状态机

使用Spring状态机实现订单业务

pom依赖导入


    org.springframework.statemachine
    spring-statemachine-core
    2.0.1.RELEASE



    org.springframework.boot
    spring-boot-autoconfigure
    2.6.8

订单类

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;
    }
}

订单状态

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 {
 
    /**
     * 配置状态
     * @param states
     * @throws Exception
     */
    public void configure(StateMachineStateConfigurer states) throws Exception {
        states.withStates().initial(OrderStatus.WAIT_PAYMENT).states(EnumSet.allOf(OrderStatus.class));
    }
 
    /**
     * 配置状态转换事件关系
     * @param transitions
     * @throws Exception
     */
    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);
    }
 
    /**
     * 持久化配置
     * 实际使用中,可以配合redis等,进行持久化操作
     * @return
     */
    @Bean
    public DefaultStateMachinePersister persister(){
        return new DefaultStateMachinePersister<>(new StateMachinePersist() {
            @Override
            public void write(StateMachineContext context, Order order) throws Exception {
                //此处可以对订单状态进行持久化操作
            }
 
            @Override
            public StateMachineContext read(Order order) throws Exception {
                //此处直接获取order中的状态,其实并没有进行持久化读取操作
                return new DefaultStateMachineContext(order.getStatus(), null, null, null);
            }
        });
    }
}

订单状态监听,并根据状态机配置做出相应的事件

@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;
    }
}

订单服务接口

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<>();

    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 getOrders() {
        return orders;
    }
 
 
    /**
     * 发送订单状态转换事件
     *
     * @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;
    }
}

打印结果

线程名称:主线程 尝试支付,订单号:1
支付,状态机反馈信息:{order=订单号:1, 订单状态:WAIT_DELIVER, id=ee9f1da9-c0f0-0305-01ca-41cba1b591af, timestamp=1654393420238}
线程名称:主线程 尝试支付,订单号:2
线程名称:客户线程 尝试发货,订单号:1
支付,状态机反馈信息:{order=订单号:2, 订单状态:WAIT_DELIVER, id=0bc9a66f-dc74-4490-26f7-82f656a36c83, timestamp=1654393421262}
线程名称:主线程 尝试发货,订单号:2
发货,状态机反馈信息:{order=订单号:2, 订单状态:WAIT_RECEIVE, id=e8e48269-b184-f238-aac2-ddcc48cc59c5, timestamp=1654393422267}
线程名称:主线程 尝试收货,订单号:2
发货,状态机反馈信息:{order=订单号:1, 订单状态:WAIT_RECEIVE, id=b4753603-a89e-7599-ac38-50f118aa048c, timestamp=1654393421263}
线程名称:客户线程 尝试收货,订单号:1
收货,状态机反馈信息:{order=订单号:2, 订单状态:FINISH, id=bd30bf3c-75a6-839a-9751-02bada949dc8, timestamp=1654393423269}
全部订单状态:{1=订单号:1, 订单状态:WAIT_RECEIVE, 2=订单号:2, 订单状态:FINISH}
收货,状态机反馈信息:{order=订单号:1, 订单状态:FINISH, id=dad2da8e-2e5e-0786-7b20-fcbf713ab5ea, timestamp=1654393424272}

你可能感兴趣的:(设计模式,状态模式,设计模式)