image.png
1.什么是AOP
就是吧我們某個方法的功能提出來與一批對象進行隔離,這樣與一批對象之間降低耦合性,就可以對某個功能進行編程;
OOP:面對對象編程
Android面向對象的七大服務:
image.png
AOP:面向切面編程
假如在上面的七大服務中,添加一個日志服務,如果面向對象的思維,日志模塊需要暴露一個調用接口,每個模塊去調用日志模塊方法,這樣產生的問題:
- 每個模塊都含有日志模塊的方法,產生了耦合,違背了模塊單一原則;
- 日志模塊改動會導致其他模塊也都需要改動,牽一發動全身;
2.AOP的意義:解耦合
把某個功能統一集中起來,集中處理,跨模塊進行編程;
例子:
每一個模塊都有自己的功能,比如圖書瀏覽、商品模塊、數據庫模塊,現在每一個模塊度要進行一個權限檢查,如果使用普通的面向對象來進行權限檢查(判斷用戶角色),就會產生以下問題:
- 1.權限檢查的規則一旦改了,每個模塊都要改動;
- 2.各個模塊之間產生了耦合,違反單一原則;
如何解決:采用面向切片的方式
image.png
3.AOP的應用
- 日志
- 用戶行為統計
- 權限管理
4.AOP實踐
AndroidStudio中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')
}
4.1例子:
image.png
原始方法(面向對象思想):
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
*/
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");
}
}
面向切面:
定義切點:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BehaviorTrace {
String value();
int type();
}
切面:
/**
* 切面
* 你想要切下來的蛋糕
*/
@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;
}
}
業務:
@BehaviorTrace(value = "搖一搖",type = 1)
public void mShake(View view)
{
SystemClock.sleep(3000);
Log.i(TAG," 搖到一個嫩模: 約不約");
}