1. 程式人生 > >觀察者模式+AOP 代碼示例

觀察者模式+AOP 代碼示例

代碼 cut ace ceo erb pointcut tty exec HR

背景

當經紀人創建客戶時,需要給對應的經紀人增加戰報信息。在代碼層面上,客源的相關類只針對客源數據表操作。而戰報信息包含了多種業務統計數據,客源只是其中統計的部分數據。鑒於兩者相對獨立,且客源的戰報信息會有所修改。因此,采用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());
    }
}

觀察者模式+AOP 代碼示例