观察者模式+AOP 代码示例

背景

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

代码

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

/**
 * 战报注解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER})
@Documented
public @interface AchievementAnnotation {

    OperateEnum operate() default OperateEnum.ADD;

    enum OperateEnum{
        ADD,UPDATE,DELETE
    }
}

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

/**
 * 战报AOP
 */
@Aspect
@Component
public class AchievementAop {

    /**
     * 战报观察者列表
     */
    private List<AchievementObserver> observerList;

    public AchievementAop() {
        this.observerList = new ArrayList<>();
    }

    public List<AchievementObserver> getObserverList() {
        return observerList;
    }

    public void setObserverList(List<AchievementObserver> 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 <T>
 */
public interface AchievementObserver<T> {

    /**
     * 是否支持该对象
     * @param obj
     * @return
     */
    boolean isSupport(Object obj);

    /**
     * 操作业务数据
     * @param t
     * @throws RuntimeException
     */
    void execute(T t) throws RuntimeException;
}

客源观察者

/**
 * 客源信息的观察者
 */
@Component
public class CustomerAchievementObserver implements AchievementObserver<CustomerBase> {

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

猜你喜欢

转载自blog.51cto.com/881206524/2133760