西北大学计算机科学系面向方面的程序设计(AOP)和面向方面的软件开发方法(AOSD)课件_第1页
西北大学计算机科学系面向方面的程序设计(AOP)和面向方面的软件开发方法(AOSD)课件_第2页
西北大学计算机科学系面向方面的程序设计(AOP)和面向方面的软件开发方法(AOSD)课件_第3页
西北大学计算机科学系面向方面的程序设计(AOP)和面向方面的软件开发方法(AOSD)课件_第4页
西北大学计算机科学系面向方面的程序设计(AOP)和面向方面的软件开发方法(AOSD)课件_第5页
已阅读5页,还剩72页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Aspect-OrientedProgramming(AOP)

andAspect-orientedsoftware

development(AOSD)

面向方面的程序设计(AOP)

和面向方面的软件开发方法(AOSD)

俳口克冈]西北大学计算机科学系

(为研究生们作的报告)2003.10

2009-8-271

软件技术新动向:面向方面方法的兴起

■二十年的实践证明:面向对象的开发方法具有很强的生

命力,已为广大的软件业界所普遍采用。

■但是,对多数复杂的系统,在多种需求关注点和实现的

模块(构件、类)之间的对应中,往往出现交叉分割

(横切)的现象。即需求关注点在实现中的分散和实现

构件内容的混杂。从而导致了软件开发和维护的一系列

困难(Poortraceability,Lowerproductivity,Lesscode

reuse,Poorcodequality,Moredifficultevolution。)

■面向方面方法就是针对这些问题而产生的。它一出现就

得到业界的广泛关注。很可能,它将成为软件开发方法

发展的重要一步,引起新一轮软件开发方法和支持工具

研究和开发的热潮。

2009-8-272

讲座大纲:

■AOPAOSD的飞速发展

■基本概念和内容

■AspectJ的基本思路

(--语言的概念和结构)

■研究和开发的方向和课题

2009-8-273

internationalconferencesonAOP

■WorkshoponAspectOrientedProgramming(ECOOP1997)June1997

■IntiWorkshoponAspectOrientedProgramming(ICSE1998)April1998.

■WorkshoponAspectOrientedProgramming(ECOOP1998),Jan1998.

■IntiWorkshoponAspectOrientedProgramming(ECOOP1999),June1999.

■WorkshoponAdvancedSeparationsofConcerns(OOPSLA2000),Oct.2000.

■WorkshoponAspectsandDimensionsofConcerns(ECOOP2000),June2000.

■WorkshoponMulti-DimentionalSeparationofConcernsinSoftware

Engineering(ICSE2000),June2000.

■WorkshoponAdvancedSeparationsofConcerns(ECOOP2001),June.2001.

■WorkshoponAdvancedSeparationsofConcernsinObjectOrietedSystems

(OOPSLA2001),Oct.2001.

■WorkshoponAdvancedSeparationofConcernsinSoftware

Engineering(ICSE2001),May2001.

2009-8-274

internationalconferencesonAOSD

■the1stinternationalconferenceonAspect-oriented

softwaredevelopment.Enschede,TheNetherlands,on

April22-26,2002..

■2ndinternationalconferenceonAspect-oriented

softwaredevelopment.Boston,Massachusetts,USA,

March17-21,2003.

■the3rdInternationalConferenceonAspect-Oriented

SoftwareDevelopment.LancasterUK,March22-26

2004.

2009-8-275

WorkshoponAspect-Orientation(German)

■AOP-GI200):

WorkshoponAspect-Orientation,May3-4,2001,

UniversityofPaderborn.(Germanonly)

■AOSD-GI2002:

SecondWorkshoponAspect-OrientedSoftware

DevelopmentoftheGI,February21-22,2002,

UniversityofBonn.

■AOSD・G12003:

ThirdWorkshoponAspect-OrientedSoftware

DevelopmentoftheGI,March4-52003,

UniversityofEssen.

2009-8-276

ResearchProjects:

■SupportedSystems:

AspectC++,AspectJ,AspectR,Aspects,...

■ResearchPrototypes:

■Applications:

■Methods&Foundations:

2009-8-277

Websites:

■/

■XeroxPARC'sresearchonAOP:

■/csl/groups/sda

2009-8-278

ABibliographyofAspect-Oriented

SoftwareDevelopment

■Version1.0(502)RIACSTechnicalReport

02.06August2002

■Version1.1(694)RIACSTechnicalReport

03.01January2003

■Version1.22

{ResearchInstituteforAdvancedComputer

Science},

2009-8-279

ThefundamentalgoalofAOSD

■ThefundamentalgoalofAOSD--effective

separationofconcerns—wasenunciatedabout

30yearsago,mostnotablybyDijkstraand

Parnas.

■Thefirsttwodecadesorsoofresearchon

separationofconcernsfocusedprimarilyon

providingnewkindsofmodules,ableto

separateconcernsinnewways.Thisledtosome

keyadvances,includingabstractdatatypesand

object-orientedprogramming,whichhavehad

dramaticimpactonsoftwareengineering

researchandpractice.

2009-8-2710

Thetimeisrightforpractitionerstobeginusing

AOSDtechnology

■Theapproachessufferedfromalimitation,however:they

couldencapsulateconcernsthatalignedwiththedominant

decompositionofthesoftwareintomodulessuchas

objectsorclasses,butnotconcernsthatcutacross

multiplemodules.

■Theadventandpromulgationofaspect-oriented

programmingawakenedbroaderinterestinthearea,on

thepartofresearchersandpractitionersalike.

■ThetimeisrightforpractitionerstobeginusingAOSD

technology,forresearcherstosolvesomeofthe

challengingproblemsthatremain,andforresearchersand

practitionerstoworktogethertomakeAOSDa

mainstreamsoftwaredevelopmenttechnology.

2009-8-2711

Evolutionofsoftwareprogrammingmethodology

■machine-levelcoding

■higher-levellanguages

■structuredlanguages

■Object-orientedprogramming(OOP)

■Eachnewmethodologypresentsnewwaystodecompose

problems:machinecode,machine-independentcode,procedures,

classes,andsoon.

■Eachnewmethodologyallowedamorenaturalmappingof

systemrequirementstoprogrammingconstructs.

2009-8-2712

thenextbigstep

■OOPhasshownitsstrengthwhenitcomes

tomodelingcommonbehavior.

■However,OOPdoesnotadequatelyaddress

behaviorsthatspanovermany—often

unrelated—modules.

■Incontrast,AOPmethodologyfillsthisvoid.

AOPquitepossiblyrepresentsthenextbig

stepintheevolutionofprogramming

methodologies.

2009-8-2713

Viewthesystemasasetofconcerns

(关注点,考虑)

■Atypicalsystemmay

consistofseveralkindsof

concerns,including:

businesslogic,performance,

datapersistence,loggingand

debugging,authentication,

security,multithreadsafety,

errorchecking,andsoon.

■development-process

concerns,suchas:

comprehensibility,

maintainability,traceability,

andevolutionease.

2009-8-2714

Concerndecomposition:

Theprism(棱镜)analogy

2009-8-2715

Modularityproblems

■Scatter(分散)

■tangle(混杂)

■crosscut(横切、交叉分割)

2009-8-2716

badmodularity

scattering-spreadaround

(分散)

tangling-codeinoneregion

addressesmultipleconcerns

(混杂)

scatteringandtangling(S&T)

tendtoappeartogether;they

describedifferentfacetsof

thesameproblem

2009-8-2717

goodmodularity

separated-implementation

ofaconcerncanbetreated

^>eparateentity

localized-implementation

ofaconcernappearsinone

partofprogram

modular-above+hasa

clear,welldefined

torestofsystem

2009-8-2718

Crosscuttingconcernsinasystem

(横切、交叉划分、跨断)

■coremodule-levelrequirementsandsystem-level

requirements.

■Manysystem-levelrequirementstendtobeorthogonal

(mutuallyindependent)toeachotherandtothe

module-levelrequirements.

■System-levelrequirementsalsotendtocrosscutmany

coremodules.

■Forexample,authentication,logging,resourcepooling,

administration,performance,andstoragemanagement.

■Eachcrosscutsseveralsubsystems.

■Forexample,astorage-managementconcernaffects

everystatefulbusinessobject.

2009-8-2719

Crosscuttingconcernproblems

■therequirementspaceisann-dimensional

space,whereastheimplementationspaceis

one-dimensional.

■Suchamismatchresultsinanawkward

requirements-to-implementationmap.

■Symptoms(症状):Codetangling;Code

scattering.

■Implications(导致):Poortraceability,

Lowerproductivity,Lesscodereuse,Poor

codequality,Moredifficultevolution.

■Thecurrentresponse:mix-inclasses,

designpatterns,anddomain-specific

solutions.

2009-8-2720

ThefundamentalsofAOP

■ThemodularizationunitinAOPiscalledanaspect,justasa

commonconcern'simplementationinOOPiscalledaclass.

■AOPinvolvesthreedistinctdevelopmentsteps:Aspectual

decomposition,Concernimplementation,Aspectual

recomposition.

2009-8-2721

example

■publicclassCreditCardProcessor{

publicvoiddebit(CreditCardcard,Currencyamount)

throwsInvalidCardException,NotEnoughAmountException,

CardExpiredException{

//Debitinglogic(取款)

}

publicvoidcredit(CreditCardcard,Currencyamount)

throwsInvalidCardException{

//Creditinglogic(存款)

}

}

■publicinterfaceLogger{

publicvoidlog(Stringmessage);

}

2009-8-2722

weavingrules

■Logeachpublicoperation'sbeginning

■Logeachpublicoperation'scompletion

■Loganyexceptionthrownbyeach

publicoperation

2009-8-2723

theweaverwouldproducecomposedcode:

publicclassCreditCardProcessorWithLogging{

LoggerJogger;

publicvoiddebit(CreditCardcard,Moneyamount)

throwsInvalidCardException,NotEnoughAmountException,

CardExpiredException{

_logger.log("StartingreditCardProcessor.credit(CreditCard,

Money)"+"Card:"+card+"Amount:"+amount);

//Debitinglogic

_logger.log("CompletingCreditCardProcessor.credit(CreditCard,

Money)"+"Card:"+card+"Amount:"+amount);

}

2009-8-2724

publicvoidcredit(CreditCardcard,Moneyamount)

throwsInvalidCardException{

System.out.println("Debiting");

_logger.log("StartingCreditCardProcessor.debit

(CreditCard,Money)''+"Card:"+card+"Amount:"+

amount);

//Creditinglogic

_logger.log("CompletingCreditCardProcessor.credit

(CreditCard,Money)''+"Card:"+card+"Amount:"+

amount);

}

}

2009-8-2725

Anatomy(解剖)ofAOPlanguages

■TheAOPlanguagespecification

■Implementationofconcerns

■Weavingrulesspecificationn:alanguagefor

specifyingrulesforcomposingdifferent

implementationpiecestoformthefinalsystem.

■AOPlanguageimplementation

■Combinetheindividualconcerns

■Converttheresultinginformationintoexecutable

code

2009-8-2726

implementtheweaverinvariousways

■source-to-sourcetranslation

■preprocesssourcecodeforindividualaspectsto

produceweavedsourcecode

■feedthisconvertedcodetothebaselanguage

compilertoproducefinalexecutablecode.

■aJava-basedAOPimplementation

■convertindividualaspectsfirstintoJavasourcecode,

thenlettheJavacompilerconvertitintobytecode.

■Thesameapproachcanperformweavingatthebyte

codeleve

■aVMimplementation

2009-8-2727

AOPbenefits

AOPhelpsovercometheproblemscausedbycodetangling

andcodescattering.HereareotherspecificbenefitsAOP

offers:

■Modularizedimplementationofcrosscuttingconcerns

■Easier-to-evolvesystems

■Latebindingofdesigndecisions

■Morecodereuse

Ingeneral,alooselycoupledimplementationrepresentsthe

keytohighercodereuse.AOPenablesmoreloosely

coupledimplementationsthanOOP.

2009-8-2728

AspectJ

LearnAspectJtobetter

understandaspect-

orientedprogramming

2009-8-2729

AspectJ:AnAOPimplementationforJava

■AspectJ,fromXeroxPARC,isageneral-purpose

aspect-orientedJavaextension.

■AspectJusesJavaasthelanguageforimplementing

individualconcerns,anditspecifiesextensionstoJava

forweavingrules.Theserulesarespecifiedinterms

of:

1.(联结点、交汇点)definespecificpointsina

program'sexecution,

2.Pointcuts(切入点、指定切入点)isthelanguageconstruct

thatspecifiesjoinpoints,

3.Advice(告知)definespiecesofanaspectimplementation

tobeexecutedatpointcuts,

4.aspects(方面)combinestheseprimitives.

■AspectJ'sweaver-anaspectcompiler-combines

differentaspectstogether.

2009-8-2730

AspectJoverview

■AspectJisalanguagespecificationaswellasanAOP

languageimplementation.

■Thelanguagespecificationdefinesvariousconstructs

andtheirsemanticstosupportaspect-orientedconcepts.

AspectJ'slanguageconstructsextendtheJava

programminglanguage.

■Thelanguageimplementationofferstoolsforcompiling,

debugging,anddocumentingcode.AspectJprovides

anaspectweaverintheformofacompiler,anaspect-

awaredebuggeranddocumentationgenerator,anda

standaloneaspectbrowsertovisualizehowanadvice

crosscutsasystem'sparts.

2009-8-2731

AspectJlanguageoverview

TosupportAOP,AspectJaddstotheJavalanguage

concepts:

■Joinpoints:Pointsinaprogram'sexecution.For

example,joinpointscoulddefinecallstospecific

methodsinaclass

■Pointcuts:Programconstructstodesignate

joinpointsandcollectspecificcontextatthose

points

■Advices:Codethatrunsuponmeetingcertain

conditions.Forexample,anadvicecouldloga

messagebeforeexecutingajoinpoint

2009-8-2732

asimpleclasscontainingmethodsto

printamessage:HelloWorld

■〃HelloWorld.java

publicclassHelloWorld{

publicstaticvoidsay(Stringmessage){

System.out.println(message);

}

publicstaticvoidsayToPerson(Stringmessage,

Stringname){

System.out.println(name+","+message);

}

}

2009-8-2733

addinggreetingandgratitude

manners.

■〃MannersAspect.java

publicaspectMannersAspect{

pointcutcallSayMessage():call(publicstatic

voidHelloWorld.say*(..));

before():callSayMessage(){

System.out.println("Goodday!");

}

after():callSayMessage(){

System.out.println("Thankyou!");

}

}

2009-8-2734

addinggreetingandgrgj31^

/TheMannersAspect.java

manners.filedeclaresa

MannersAspectaspect.

■〃MannersAspect.javaTheaspectdefinesa

callSayMessage()pointcut

publicaspectMannersAspethatcapturescallstoall

pointcutcallSayMessage(publicstaticmethodswith

namesthatstartwithsay.

voidHelloWorld.ScItwouldcapturesay()and

before():callSayMessagsayToPerson()ina

System.out.println("GoHelloWorldclass.

)Thenyoudefinetwo

advicesforbeforeand

afterreachingthe

after():callSayMessage(callSayMessage()pointcut:

System.out.printin("Thprinting"Goodday!"and

}"Thankyou!"

}

2009-8-2735

AspectJlanguageconceptsand

constructs--1

■JoinpointsJoinpoints,acentralconceptinAspectJ,are

well-definedpointsinaprogram'sexecution.

■Candidatejoinpointsinclude

■callstoamethod,

■aconditionalcheck,

■aloop'sbeginning,

■oranassignment.

■Joinpointsalsohaveacontextassociatedwiththem.For

example,amethod-calljoinpointcouldhavethetarget

objectanditsargumentaspartofthecontext.

2009-8-2736

AspectJlanguageconceptsand

constructs--2

■Pointcuts,programconstructstodesignatejoinpoints,

letyouspecifyajoinpointcollection.Pointcutsalsolet

youexposecontextatthejoinpointtoanadvice

implementation.

■AspectJmakesthefollowingpointcutsavailable:

■Methodcallandexecution

■Constructorcallandexecution

■Read/writeaccesstoafield

■Exceptionhandlerexecution

■Objectandclassinitializationexecution

■H㊀iioWoridexample:pointcutcallSayMessage():

call(publicstaticvoidHelloWorld.say*(..));

2009-8-2737

Table1.Calltomethodsandconstructors

pointcuts—callpointcuts

call(publicvoidCalltomyMethod()inMyClass

MyClass.myMethod(String))takingastringargument,

returningvoid,andwithpublic

access

call(voidCalltomyMethod()inMyClass

MyClass.myMethod(..))takinganyarguments,withvoid

returntype,andanyaccess

modifiers

call(*CalltomyMethod()inMyClass

MyClass.myMethod(..))takinganyargumentsreturning

anytype

call(*Calltoanymethodwithname

MyClass.myMethod*(..))Startingin"myMethod"inMyClass

call(夫Calltoanymethodwithname

MyClass.myMethod*(StringStartingin"myMethod"inMyClass

,••))andthefirstargumentisof

Stringtype

zuuy-«-z/38

call(**.myM㊀thod(・・))CalltomyM㊀thod()inany

classindefaultpackage

call(MyClass.n㊀w())CalltoanyMyClass'

constructortakingno

arguments

call(MyClass.naw(..))CalltoanyMyClass'

constructorwithany

arguments

call(MyClass+.naw(..))CalltoanyMyClassorits

subclass'sconstructor.

(Subclassindicatedbyuse

ofwildcard)

call(public*Allpublicmethodsinall

com.mycompany,・文・*(・・))classesinanypackagewith

com.mycompanytheroot

package

2009-8-2739

Table2.Executionofmethodsandconstructors

pointcuts—executionpointcuts

execution(publicvoidExecutionOfmyMethod()inMyClass

MyClass.myMethod(Strintakingastringargument,returning

g))void,andwithpublicaccess

execution(voidExecutionOfmyMethod()inMyClass

MyClass.myM㊀thoci(..))takinganyarguments,withvoid

returntype,andanyaccessmodifiers

execution(*ExecutionOfmyMethod()inMyClass

MyClass.myMethod(..))takinganyargumentsreturningany

type

execution(*Executionofanymethodwithname

MyClass.myMethod*(..))Startingin"myMethod"inMyClass

execution(*Executionofanymethodwithname

MyClass.myMethod*(Stristartingin"myMethod"inMyClassand

ng,..))thefirstargumentisofstringtype

2009-8-2740

㊀x㊀cution(*ExecutionofmyMethodOin

*.mybfethod(..))anyclassindefaultpackage

㊀x㊀cution(MyClass.n㊀ExecutionofanyMyClass'

w())constructortakingno

arguments

㊀x㊀cution(MyClass.n㊀ExecutionofanyMyClass'

w(..))constructorwithany

arguments

㊀x㊀cution(MyClass+.nExecutionofanyMyClassor

㊀w(..))itssubclass'sconstructor.

(Subclassindicatedbyuse

of'+'wildcard)

㊀x㊀cution(public*Allpublicmethodsinall

com.mycompany..*.*(.classesinanypackagewith

.))com.mycompanytheroot

package

2009-8-2741

Table3.Field-accesspointcuts

gat(PrintStr㊀amExecutionofread-accesstofield

Syst㊀m.out)outoftypePrintStr㊀amin

Syst㊀mclass

s㊀t(intMyClass.x)Executionofwrite-accesstofieldx

OftypeintinMyClass

Table4.Exception-handlerpointcuts

hander(R㊀mot㊀Exc㊀ptiExecutionofcatch-block

on)handlingR㊀mot㊀Exceptiontype

hander(工OExc㊀ption+)Executionofcatch-block

handlinglOExceptionorits

subclasses

handl㊀r(Cr㊀ditCard*)Executionofcatch-block

handlingexceptiontypeswith

namesthatstartwith

Cr㊀ditCard

2009-8-2742

Table5.Class-initializationpointcuts

staticinitialization(Executionofstaticblockof

MyClass)MyClass

Staticinitialization(Executionofstaticblock

MyClass+)ofMyClassorits

subclass㊀s

Table6.Lexical-structure-basedpointcuts

ithin(MyClass)AnypointcutinsideMyciass's

lexicalscope

ithin(MyClass*)Anypointcutinsidelexicalscope

ofclasseswithanamethat

startswith"MyClass"

withincod㊀(*Anypointcutinsidelexicalscope

MyClass.myM㊀thod(・・))ofanymyM㊀thod()ofMyClass

2009-8-2743

Table7.Control-flow-basedpointcuts

cflow(call(火Allthejoinpointsincontrolflowofcallto

MyClass.myMethod(anymyMethod()inMyClassincludingcall

..))tothespecifiedmethoditself

cflowbelow(call(大Allthejoinpointsincontrolflowofcallto

MyClass.myMethod(anymyMethod()inMyClassexcludingcall

・.))tothespecifiedmethoditself

Table8.Self-,target",andarguments-typepointcuts

this(JComponentAllthejoinpointswherethisisinstanceof

+)JComponent

target(MyClass)Allthejoinpointswheretheobjectonwhich

themethodiscalledisoftypeMyClass

args(String,..,Allthejoinpointswherethefirstargumentis

int)ofStringtypeandthelastargumentisofint

type

args(RemoteExceAllthejoinpointswherethetypeofargument

ption)orexceptionhandlertypeisRemoteException

2009-8-271:-^4

Table9.Conditional-testpointcuts

Lf(EventQueue.isDispatAllthejoinpointswhere

(^hThread())EventQueue.isDispatchThread()

evaluatestotrue

•Namedandanonymouspointcuts

•Use11,&&,and!operatorswithpointcuts

Forexample,

call(*MyClass.ml())||call(*MyClass.m2())

call(*MyClass.ml())&&cflow(call(*MyClass.m2())

!call(*MyClass.ml())

2009-8-2745

Exposingcontext

■AspectJofferstarget(),this(),and

args()pointcutstocollectthecontext,

■Forexample,

pointcut

publicOperationCardAmountArgs(Credi

tCardcard,Moneyamount):

execution(public火

CreditCardProcessor・*(・・))&&

args(card,amount);

2009-8-2746

AspectJlanguageconceptsand

constructs-3

•Advicesspecifytheexecutablecodewhenreaching

certainpointcuts.

•AspectJprovidesthreewaystoassociateanadvicewith

ajoinpoint:

•Abeforeadvicerunsjustbeforethejoinpoint,

•whereasanafteradvicerunsjustafter.

•Anaroundadvicesurroundsajoinpointandhas

controlifthejoinpoint'sexecutionshouldproceed.

2009-8-2747

before():call(public*MyClass.*(..)){

System.out.println(nBefore:''+thisJoinPoint+''''+

System.currentTimeMillisO);

}

after():call(public*MyClass.*(..)){

System.out.println(nAfter:''+thisJoinPoint+"”+

System.currentTimeMillisQ);

voidaround(Connectionconn):calI(Connection.close())&&target(conn){

if(enablePooling){

connectionPool.put(conn);

}else{

proceedQ;

2009-8-2748

AspectJlanguageconceptsand

constructs-4

•AspectsactasAspectJ'sunitofmodularization.Itputs

togetherpointcutsandadvices.

•Aspectsresembleclasses:anaspectcancontain

methodsandfields,extendotherclassesoraspects,and

implementinterfaces.However;youcannotcreatean

objectforanaspectusingn㊀w.

•AspectJdoesnotallowclassestocontainadvices;only

aspectscancontainadvices.

•Aconcreteaspectextendinganabstractaspectcanthen

provideconcretedefinitionsofabstractpointcuts.

2009-8-27

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论