千家信息网

观察者模式+AOP 代码示例

发表于:2024-10-18 作者:千家信息网编辑
千家信息网最后更新 2024年10月18日,背景当经纪人创建客户时,需要给对应的经纪人增加战报信息。在代码层面上,客源的相关类只针对客源数据表操作。而战报信息包含了多种业务统计数据,客源只是其中统计的部分数据。鉴于两者相对独立,且客源的战报信息
千家信息网最后更新 2024年10月18日观察者模式+AOP 代码示例

背景

当经纪人创建客户时,需要给对应的经纪人增加战报信息。在代码层面上,客源的相关类只针对客源数据表操作。而战报信息包含了多种业务统计数据,客源只是其中统计的部分数据。鉴于两者相对独立,且客源的战报信息会有所修改。因此,采用AOP+观察者模式构建代码。

代码

定义一个注解,用于AOP拦截。

/** * 战报注解 */@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD, ElementType.PARAMETER})@Documentedpublic @interface AchievementAnnotation {    OperateEnum operate() default OperateEnum.ADD;    enum OperateEnum{        ADD,UPDATE,DELETE    }}

定义AOP,用户获取数据,并转发给观察者

/** * 战报AOP */@Aspect@Componentpublic class AchievementAop {    /**     * 战报观察者列表     */    private List observerList;    public AchievementAop() {        this.observerList = new ArrayList<>();    }    public List getObserverList() {        return observerList;    }    public void setObserverList(List observerList) {        if (null != this.observerList)            this.observerList.addAll(observerList);        this.observerList = observerList;    }    /**        *注入客源的观察者        */    @Autowired    public void setCustomerAchievementObserver(CustomerAchievementObserver customerAchievementObserver) {        getObserverList().add(customerAchievementObserver);    }    @Pointcut("@annotation(com.pretang.cloud.aop.AchievementAnnotation)")    private void pointCut() {    }    @AfterReturning(pointcut = "pointCut()", returning = "retVal")    public void after(JoinPoint joinPoint, Object retVal) {        Signature signature = joinPoint.getSignature();        MethodSignature methodSignature = (MethodSignature) signature;        Method targetMethod = methodSignature.getMethod();        AchievementAnnotation annotation = targetMethod.getAnnotation(AchievementAnnotation.class);        AchievementAnnotation.OperateEnum operateEnum = annotation.operate();        for (AchievementObserver observer : observerList) {            if (observer.isSupport(retVal))                observer.execute(retVal);        }    }}

定义观察者通用接口

/** * 战报信息观察者接口 * @param  */public interface AchievementObserver {    /**     * 是否支持该对象     * @param obj     * @return     */    boolean isSupport(Object obj);    /**     * 操作业务数据     * @param t     * @throws RuntimeException     */    void execute(T t) throws RuntimeException;}

客源观察者

/** * 客源信息的观察者 */@Componentpublic class CustomerAchievementObserver implements AchievementObserver {    @Autowired    private CustomerRpcService customerRpcService;    @Override    public boolean isSupport(Object obj) {        return obj instanceof CustomerBase;    }    @Override    public void execute(CustomerBase customerBase) throws RuntimeException {            // 实际业务处理        customerRpcService.saveAchievement(customerBase.getAgentUserId(), "ADD_CUSTOMER", customerBase.getId());    }}
0