aop面向切面编程

aop面向切面编程

  • AOP(Aspect-Oriented Programming,面向切面的编程),它是可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。它是一种新的方法论,它是对传统OOP编程的一种补充。

  • OOP是关注将需求功能划分为不同的并且相对独立,封装良好的类,并让它们有着属于自己的行为,依靠继承和多态等来定义彼此的关系;AOP是希望能够将通用需求功能从不相关的类当中分离出来,能够使得很多类共享一个行为,一旦发生变化,不必修改很多类,而只需要修改这个行为即可。

  • AOP是使用切面(aspect)将横切关注点模块化,OOP是使用类将状态和行为模块化。在OOP的世界中,程序都是通过类和接口组织的,使用它们实现程序的核心业务逻辑是十分合适。但是对于实现横切关注点(跨越应用程序多个模块的功能需求)则十分吃力,比如日志记录,验证。

  • aop面向切面链接

    下载aspectj 地址 http://www.eclipse.org/aspectj/downloads.php

    下载aspectj的adt地址http://www.eclipse.org/ajdt/downloads/#43zips

    build.gradle aspectJ 写法 http://fernandocejas.com/2014/08/03/aspect-oriented-programming-in-android/

  • android studio使用aop面向切面编程

配置项目builder.gradle文件

import org.aspectj.bridge.IMessage
import org.aspectj.bridge.MessageHandler
import org.aspectj.tools.ajc.Main
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.aspectj:aspectjtools:1.8.9'
        classpath 'org.aspectj:aspectjweaver:1.8.9'
    }
}

apply plugin: 'com.android.application'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.1'
    defaultConfig {
        applicationId "com.example.administrator.dn_02_aop"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

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.8",
                         "-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;
            }
        }
    }
}



dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.0.0'
    testCompile 'junit:junit:4.12'
    compile files('libs/aspectjrt.jar')
}

核心代码BehaviorTrace.java

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BehaviorTrace {
    String value();
    int type();
}
MainActivity.java

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "dongnao";
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /**
     * 摇一摇的模块
     *
     * @param view
     */
    @BehaviorTrace(value = "摇一摇",type = 1)
    public  void mShake(View view)
    {
            SystemClock.sleep(3000);
            Log.i(TAG,"  摇到一个嫩模:  约不约");
    }


    /**
     * 语音的模块
     *
     * @param view
     */
    public  void mAudio(View view)
    {
        long beagin=System.currentTimeMillis();

        //摇一摇的代码逻辑
        {
            SystemClock.sleep(3000);

            Log.i(TAG,"  美女  睡不着   热不热");

        }

        Log.i(TAG,"消耗时间:  "+(System.currentTimeMillis()-beagin)+"ms");
    }

    /**
     * 发送文本的模块
     *
     * @param view
     */
    public  void mText(View view)
    {
        //统计用户行为 的逻辑
        Log.i(TAG,"文字:  使用时间:   "+simpleDateFormat.format(new Date()));
        long beagin=System.currentTimeMillis();

        //摇一摇的代码逻辑
        {
            SystemClock.sleep(3000);
            Log.i(TAG,"  热   我们去18");

        }

        Log.i(TAG,"消耗时间:  "+(System.currentTimeMillis()-beagin)+"ms");
    }

}

BehaviorAspect.java

/**
 * 切面
 * 你想要切下来的蛋糕
 */
@Aspect
public class BehaviorAspect {
    private static final String TAG = "dongnao";
    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 如何切蛋糕,切成什么样的形状
     * 切点
     */
    @Pointcut("execution(@com.example.administrator.dn_02_aop.BehaviorTrace  * *(..))")
    public void annoBehavior()
    {

    }

    /**
     * 切面
     * 蛋糕按照切点切下来之后   怎么吃
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("annoBehavior()")
    public Object dealPoint(ProceedingJoinPoint point) throws  Throwable
    {
        //方法执行前
        MethodSignature methodSignature= (MethodSignature) point.getSignature();
        BehaviorTrace  behaviorTrace=methodSignature.getMethod().getAnnotation(BehaviorTrace.class);
        String contentType=behaviorTrace.value();
        int type=behaviorTrace.type();
        Log.i(TAG,contentType+"使用时间:   "+simpleDateFormat.format(new Date()));
        long beagin=System.currentTimeMillis();
        //方法执行时
        Object object=null;
        try {
             object=point.proceed();
        }catch (Exception e)
        {

        }
        //方法执行完成
        Log.i(TAG,"消耗时间:  "+(System.currentTimeMillis()-beagin)+"ms");

        return  object;
    }
}













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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值