当涉及到电商场景时,观察者模式可以用于处理多种情况,比如订单状态更新、库存变化、用户积分变化等。下面是一个简化的订单状态更新的观察者模式案例。
1.首先,定义一个主题接口 OrderSubject
/*** Description:主题,用于管理观察者** @author: wubei* @date: 2023/12/6 14:09*/
public interface OrderSubject {void addObserver(OrderObserver observer);void removeObserver(OrderObserver observer);void notifyObservers(OrderStatus status);}
2.然后,定义一个观察者接口 OrderObserver
/*** Description:** @author: wubei* @date: 2023/12/6 14:09*/
public interface OrderObserver {void update(OrderStatus status);}
3.接下来,定义订单状态枚举 OrderStatus
/*** Description:** @author: wubei* @date: 2023/12/6 14:10*/
public enum OrderStatus {CREATED, SHIPPED, DELIVERED, CANCELLED}
4.然后,实现具体的订单主题类 Order
/*** Description:* Order 类充当主题(Subject),而 CustomerService 和 Warehouse 类充当观察者(Observer)。* 当订单状态发生变化时,所有注册的观察者都会收到通知,并执行相应的更新逻辑。* 这个模式可以轻松扩展以处理更多的观察者和主题。** @author: wubei* @date: 2023/12/6 14:10*/
public class Order implements OrderSubject {private List<OrderObserver> observers = new ArrayList<>();private OrderStatus status;public Order(OrderStatus status) {this.status = status;}public OrderStatus getStatus() {return status;}public void setStatus(OrderStatus status) {this.status = status;notifyObservers(status);}@Overridepublic void addObserver(OrderObserver observer) {observers.add(observer);}@Overridepublic void removeObserver(OrderObserver observer) {observers.remove(observer);}@Overridepublic void notifyObservers(OrderStatus status) {for (OrderObserver observer : observers) {observer.update(status);}}
}
5.接下来,创建两个具体的观察者类,分别处理订单状态的更新
/*** Description:** @author: wubei* @date: 2023/12/6 14:10*/
@Slf4j
public class CustomerService implements OrderObserver {@Overridepublic void update(OrderStatus status) {log.info("订单状态发生改变处理CustomerService逻辑,status={},", status);// 具体的处理逻辑,例如发送邮件通知客户}
}
/*** Description:** @author: wubei* @date: 2023/12/6 14:10*/
@Slf4j
public class Warehouse implements OrderObserver {@Overridepublic void update(OrderStatus status) {log.info("订单状态发生改变处理Warehouse逻辑,status={},", status);// 具体的处理逻辑,例如更新库存}}
6.最后,在主应用程序中使用这些类
public class Main {public static void main(String[] args) {Order order = new Order(OrderStatus.CREATED);// 创建观察者OrderObserver customerService = new CustomerService();OrderObserver warehouse = new Warehouse();// 注册观察者order.addObserver(customerService);order.addObserver(warehouse);// 模拟订单状态变化order.setStatus(OrderStatus.SHIPPED);order.setStatus(OrderStatus.DELIVERED);}
}
执行结果:
14:49:40.081 [main] INFO com.ft.beanPostProcessor.custom1.CustomerService - 订单状态发生改变处理CustomerService逻辑,status=SHIPPED,
14:49:40.082 [main] INFO com.ft.beanPostProcessor.custom1.Warehouse - 订单状态发生改变处理Warehouse逻辑,status=SHIPPED,
14:49:40.082 [main] INFO com.ft.beanPostProcessor.custom1.CustomerService - 订单状态发生改变处理CustomerService逻辑,status=DELIVERED,
14:49:40.082 [main] INFO com.ft.beanPostProcessor.custom1.Warehouse - 订单状态发生改变处理Warehouse逻辑,status=DELIVERED,