移动架构10_面向切面设计AOP

来源:互联网 发布:生命周期假说 知乎 编辑:程序博客网 时间:2024/06/09 20:46

通俗的概述本文:面向对象有时在封装一个模块后,其他很多模块调用他,修改性和耦合性差,因此引入面向切面设计。面向切面设计,发生在代码编译期,不会影响性能,通过在其它模块加标记(注解),统一到一个地方进行处理。该方法要安装AspectJ,同时配置项目

Demo地址:(要先安装AspectJ)http://download.csdn.net/download/baopengjian/10008236

在项目中,面向设计的思想一般会解决90%的问题,但在特定条件下,面向对象有其局限性:
ss
如上图,当定义了模块1用于权限检查,其他模块使用该功能时,进行模块间调用,但是如果规则发生了改变,那么所有调用1的地方都要进行修改;而且在各个具体模块的方法中,本来是对一个功能的封装,现在掺杂了其他模块的功能,封装性不好。为了解决这类问题,同时解决多个功能调用相同模块的耦合性,就引出了面向切面设计编程思想。

一、概念
什么是AOP?
把我们某个方面的功能提取出来与一批对象进行隔离,这样与一批对象之间降低耦合性,对某个功能进行编程
如图:
ss
根据切点切面,切出一个单独的某块进行操作。

AOP的意义:
解决面向对象解决不了的跨模块编程问题。解耦,把某一个功能集中起来,放到一个地方统一进行管理

AOP的应用
j2ee
Android:用户行为统计、权限管理

AOP实践
在使用的地方进行标记(注解),然后统一进行处理,若果需要修改,则仅仅只需修改一份代码即可。
(1)AspectJ(一个工具)
(2) 三个概念
aspect 切面
Pointcut 切点
Around 处理

AspectJ是一个面向切面的框架,他扩展了java语言所以它有一个专门的编译器生成遵守java字节码规范的Class文件(不通过javac)


(1)下载aspectj并安装
aspectj 地址 http://www.eclipse.org/aspectj/downloads.php

(2)开发工具配置
1)Eclipse中,
第一步,右击项目-Configure-convert to AspectJ Point,如果没有,则要下载对应的adt插件:
下载aspectj的adt地址http://www.eclipse.org/ajdt/downloads/#43zips
第二步,Java BuildPath - 去掉Android PrivateLibrary ,勾选AspectJ Runtime Library
注意:Eclipse版本和对应AspectJ的版本要一致
第三不,将aspectJ安装路径的lib目录下的aspectjrt.jar包拷贝到项目的lib目录中去

2)使用AndroidStudio开发:
需要配置,build.gradle ,同时也需要添加aspectjrt.jar包
例如:
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')
}
aspectJ 写法 :http://fernandocejas.com/2014/08/03/aspect-oriented-programming-in-android/


代码:
1、MainActivity中原始代码(3个click方法):

/**
* 摇一摇的模块
*
* @param view
*/
public void mShake(View view)
{
long beagin=System.currentTimeMillis();
{
SystemClock.sleep(3000);

Log.i(TAG," 摇一摇的模块");

}

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


/**
* 语音的模块
*
* @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,"一摇的模块");

}

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

可以看到三个点击实际中都有统计,可以利用面向切面设计思想,在方法上加上标记(注解),然后单独出来,这里只对第一个方法进行处理

2、定义标记(注解)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BehaviorTrace {
String value();
int type();
}

3、使用标记
MainActivity中mShake改写,去掉统计代码,加上注解,传入参数:
@BehaviorTrace(value = "摇一摇",type = 1)
public void mShake(View view)
{
SystemClock.sleep(3000);
Log.i(TAG," 摇到一个嫩模: 约不约");
}

4、统一处理逻辑

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


}

运行结果和原始代码一样