架构设计分析(七)AOP架构设计

来点前奏说明

当你打开这个文档的时候,你已经做好准备了,话不多说开搞。
本文以Android 9.0 版本进行分析,当然你也可以在线看源码在线源码查看Android源码下载编译9.0源码下载链接 提取码:d0ks
在此特别说明,这篇文档参考了很多文章和视频,主要自己记录一下,有些我也不明白。

什么是OOP:

OOP(ObjectOriented Programming)面向对象编程,把功能或者问题模块化,每个模块处理自己的。

什么是AOP:

AOP是Aspect Oriented Programming 意思是面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。在运行时、编译时、类加载期,动态的将代码切入到类的指定方法、指定位置上的编程思想。

AOP和OOP的区别和联系:
  • AOP在编程历史上可以说是里程碑式的,对OOP编程是一种十分有益的补充。
  • AOP像OOP一样,只是一种编程方法论,AOP没有规定说实现AOP协议的代码,要用什么方式去实现。
  • OOP侧重静态、名词、状态、组织、数据,载体是空间;
    AOP侧重动态、动词、行为、调用、算法,载体是时间。
使用AOP的好处:
  • 利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
  • 容易扩展辅助功能
使用AOP思想的常见的三方框架
  • Butterknife
  • EventBus
  • ........
AspectJ

AspectJ实际上是对AOP编程思想的一个实践,是一个面向切面编程的框架。它是java的扩展,而且完全减重java。它有一个专门的编译器用来生成遵守java字节编码规范的class文件,支持原生的java只需要加上AspectJ提供的注解即可。在android开发中,一般用它提供的注解和一些简单的语法就可以实现大部分功能上的需求。

怎么使用
  • 非组件化接入 作为项目一部分
  1. 在项目的build.gradle的dependencies中添加
classpath 'org.aspectj:aspectjtools:1.9.4'

1.1 在app下的build.gradle的dependencies中添加

implementation 'org.aspectj:aspectjrt:1.9.6'

1.2 在app下的build.gradle同样添加

import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main

final def log = project.logger
final def variants = project.android.applicationVariants


//在构建工程时,执行编辑
variants.all { variant ->
    if (!variant.buildType.isDebuggable()) {
        log.debug("Skipping non-debuggable build type '${variant.buildType.name}'.")
        return;
    }

    JavaCompile javaCompile = variant.javaCompile
    javaCompile.doLast {
        String[] args = ["-showWeaveInfo",
                         "-1.9",
                         "-inpath", javaCompile.destinationDir.toString(),
                         "-aspectpath", javaCompile.classpath.asPath,
                         "-d", javaCompile.destinationDir.toString(),
                         "-classpath", javaCompile.classpath.asPath,
                         "-bootclasspath", project.android.bootClasspath.join(File.pathSeparator)]
        log.debug "ajc args: " + Arrays.toString(args)

        MessageHandler handler = new MessageHandler(true);
        new Main().run(args, handler);
        for (IMessage message : handler.getMessages(null, true)) {
            switch (message.getKind()) {
                case IMessage.ABORT:
                case IMessage.ERROR:
                case IMessage.FAIL:
                    log.error message.message, message.thrown
                    break;
                case IMessage.WARNING:
                    log.warn message.message, message.thrown
                    break;
                case IMessage.INFO:
                    log.info message.message, message.thrown
                    break;
                case IMessage.DEBUG:
                    log.debug message.message, message.thrown
                    break;
            }
        }
    }
}

2.创建用来干嘛的注解的切入点接口 BehaviorTrace

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)

public @interface BehaviorTrace {
    String value();
}

2.1 创建一个切面类 BehaviorTraceAspect

import android.os.SystemClock;
import android.util.Log;

import com.example.aop.anotation.BehaviorTrace;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.util.Random;

@Aspect
public class BehaviorTraceAspect {
    
    @Pointcut("execution(@com.example.aop.anotation.BehaviorTrace * *(..))")
    public void methodAnotationWithBehaviorTrace(){

    }
    @Around("methodAnotationWithBehaviorTrace()")
    public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable{
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String className = methodSignature.getDeclaringType().getSimpleName();
        String methodName = methodSignature.getName();
        String value = methodSignature.getMethod().getAnnotation(BehaviorTrace.class).value();
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        SystemClock.sleep(new Random().nextInt(2000));
        long duration = System.currentTimeMillis() - begin;
        Log.d("zhangbinApp",String.format("%s类的%s方法的%s功能 执行了耗时%d ms",className,methodName,value,duration));
        return result;
    }

}

3 在MainActivity中测试

@BehaviorTrace("语音通话")
    private void mAudio() {

    }
    @BehaviorTrace("摇一摇")
    private void mShake() {

    }
  1. 输出log
2020-11-01 22:18:49.548 8364-8364/com.example.aop D/zhangbinApp: MainActivity类的
mShake方法的摇一摇功能 执行了耗时436 ms
2020-11-01 22:21:45.293 8364-8364/com.example.aop D/zhangbinApp: MainActivity类的
mAudio方法的语音通话功能 执行了耗时243 ms
2020-11-01 22:42:08.407 8364-8364/com.example.aop D/zhangbinApp: SecondActivity类的
mSay方法的发表说说功能 执行了耗时441 ms

说到此有同学会说这不就是base类吗 其实不是 只要方法加上这个注释就能执行要做什么的weaveJoinPoint这个方法 当不想使用的时候去掉注解就可以类 有木有感觉很方便呢

FAQ 问题答疑

Question1:
Answer1:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值